base_gateway.go
2.0 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
package gateway
import (
"context"
"encoding/json"
"fmt"
"github.com/zeromicro/go-zero/core/mapping"
"github.com/zeromicro/go-zero/rest/httpc"
"io/ioutil"
"net/http"
"strings"
"time"
)
type Service struct {
Timeout time.Duration
host string
Interceptor func(msg string)
ServiceName string
service httpc.Service
}
func NewService(name string, host string, timeout time.Duration, opts ...httpc.Option) Service {
client := &http.Client{}
//client.Timeout = timeout
service := Service{
host: host,
service: httpc.NewServiceWithClient(name, client, opts...),
}
return service
}
func (gateway Service) Do(ctx context.Context, url string, method string, val interface{}, result interface{}) error {
var (
baseResponse = Response{}
begin = time.Now()
body []byte
)
response, err := gateway.service.Do(ctx, method, gateway.host+url, val)
defer func() {
jsonParam, _ := json.Marshal(val)
jsonData, _ := json.Marshal(result)
if err != nil {
result = err.Error()
}
if gateway.Interceptor != nil {
gateway.Interceptor(fmt.Sprintf("【网关】%v | %v%v | %v : %v \n-->> %v \n<<-- %v", time.Since(begin), gateway.host, url, strings.ToUpper(method),
result,
string(jsonParam),
string(jsonData),
))
}
}()
if err != nil {
return err
}
if response.StatusCode != http.StatusOK {
return HttpError{
Base: Response{
Code: response.StatusCode,
Msg: response.Status,
},
}
}
body, err = Bytes(response)
if err != nil {
return err
}
if err = json.Unmarshal(body, &baseResponse); err != nil {
return err
}
if baseResponse.Code != 0 {
return HttpError{
Base: Response{
Code: baseResponse.Code,
Msg: baseResponse.Msg,
},
}
}
if err = mapping.UnmarshalJsonBytes(baseResponse.Data, result); err != nil {
return err
}
return nil
}
func Bytes(resp *http.Response) ([]byte, error) {
var body []byte
if resp.Body == nil {
return nil, nil
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
return body, err
}