httplib_service_gateway.go
1.4 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
package service_gateway
import (
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/beego/beego/v2/client/httplib"
)
type MessageCode struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
//GatewayResponse 统一消息返回格式
type GatewayResponse struct {
MessageCode
Data json.RawMessage `json:"data"`
}
type BaseServiceGateway struct {
ConnectTimeout time.Duration
ReadWriteTimeout time.Duration
CompanyId int64
OrgId int64
UserId int64
}
func (gateway BaseServiceGateway) CreateRequest(url string, method string) *httplib.BeegoHTTPRequest {
var request *httplib.BeegoHTTPRequest
switch method {
case "get":
request = httplib.Get(url)
case "post":
request = httplib.Post(url)
case "put":
request = httplib.Put(url)
case "delete":
request = httplib.Delete(url)
case "head":
request = httplib.Head(url)
default:
request = httplib.Get(url)
}
request.Header("companyId", strconv.FormatInt(gateway.CompanyId, 10))
request.Header("orgId", strconv.FormatInt(gateway.OrgId, 10))
request.Header("userId", strconv.FormatInt(gateway.UserId, 10))
return request.SetTimeout(gateway.ConnectTimeout, gateway.ReadWriteTimeout)
}
func (gateway BaseServiceGateway) GetResponseData(result GatewayResponse, 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
}