base_service_gateway.go
2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package service_gateway
import (
rawjson "encoding/json"
"errors"
"fmt"
"github.com/linmadan/egglib-go/utils/json"
"time"
"github.com/beego/beego/v2/client/httplib"
)
type MessageCode struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
//GatewayResponse 统一消息返回格式
type Response struct {
MessageCode
Data rawjson.RawMessage `json:"data"`
}
type BaseServiceGateway struct {
ConnectTimeout time.Duration
ReadWriteTimeout time.Duration
host string
}
type Request struct {
Url string
Method string
Param interface{}
}
func (gateway BaseServiceGateway) CreateRequest(url string, method string) *httplib.BeegoHTTPRequest {
var request *httplib.BeegoHTTPRequest
switch method {
case "get", "GET":
request = httplib.Get(url)
case "post", "POST":
request = httplib.Post(url)
case "put", "PUT":
request = httplib.Put(url)
case "delete", "DELETE":
request = httplib.Delete(url)
case "head", "HEADER":
request = httplib.Head(url)
default:
request = httplib.Get(url)
}
return request.SetTimeout(gateway.ConnectTimeout, gateway.ReadWriteTimeout)
}
func (gateway BaseServiceGateway) GetResponseData(result Response, data interface{}) error {
if result.Code != 0 {
return fmt.Errorf(result.Msg)
}
err := json.Unmarshal(result.Data, data)
if err != nil {
return err
}
return nil
}
func (gateway BaseServiceGateway) FastDoRequest(url, method string, param interface{}, data interface{}) error {
err := gateway.DoRequest(Request{
Url: url,
Method: method,
Param: param,
}, &data)
if err != nil {
return err
}
return nil
}
func (gateway BaseServiceGateway) DoRequest(requestParam Request, val interface{}) error {
r := gateway.CreateRequest(requestParam.Url, requestParam.Method)
req, err := r.JSONBody(requestParam.Param)
if err != nil {
return err
}
byteResult, err := req.Bytes()
if err != nil {
return err
}
var result Response
err = json.Unmarshal(byteResult, &result)
if err != nil {
return err
}
if result.Code != 0 && len(result.Msg) > 0 {
return errors.New(result.Msg)
}
err = gateway.GetResponseData(result, val)
return nil
}
func (gateway BaseServiceGateway) Host() string {
return gateway.host
}
func NewBaseServiceGateway(host string) BaseServiceGateway {
return BaseServiceGateway{
host: host,
}
}