-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
210 lines (188 loc) · 4.48 KB
/
request.go
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package simple_http
import (
"encoding/json"
"fmt"
"net/http"
"sync"
"time"
"github.com/go-resty/resty/v2"
"github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
)
const (
contentTypeJSON = "application/json"
contentTypeForm = "application/x-www-form-urlencoded"
)
var (
apiMap map[string]*ServiceAPI
apiLocker *sync.RWMutex
logger *logrus.Logger
)
func init() {
apiMap = map[string]*ServiceAPI{}
apiLocker = &sync.RWMutex{}
}
// SetLogger
//
// @param l
func SetLogger(l *logrus.Logger) {
apiLocker.Lock()
defer apiLocker.Unlock()
logger = l
}
// RegisterServiceAPI
//
// @param name
// @param api
func RegisterServiceAPI(name string, api *ServiceAPI) {
apiLocker.Lock()
defer apiLocker.Unlock()
apiMap[name] = api
}
// GetServiceAPI
//
// @param name
// @return *ServiceAPI
func GetServiceAPI(name string) *ServiceAPI {
if api, ok := apiMap[name]; ok {
return api
}
return nil
}
// RequestServiceAPIByName
//
// @param name
// @param input
// @param header
// @return *APIResponse
// @return error
func RequestByName(name string, input map[string]interface{}, header map[string]string) (*APIResponse, error) {
api := GetServiceAPI(name)
if api == nil {
return nil, fmt.Errorf("api config `%s` not found", name)
}
return RequestServiceAPI(api, input, header)
}
// RequestServiceAPI
//
// @param api
// @param input
// @param header
// @return *APIResponse
// @return error
func RequestServiceAPI(api *ServiceAPI, input map[string]interface{}, header map[string]string) (*APIResponse, error) {
response, err := DoRequest(api, input, header)
if err != nil {
return nil, err
}
if response.StatusCode() != 200 {
return nil, fmt.Errorf("http error: %v", response.Status())
}
return extractResponse(response.Body(), api), nil
}
// DoRequest
//
// @param api
// @param input
// @param header
// @return *resty.Response
// @return error
func DoRequest(api *ServiceAPI, input map[string]interface{}, header map[string]string) (*resty.Response, error) {
var (
inputNew map[string]interface{} = input
headerNew map[string]string = header
apiNew *ServiceAPI = api
err error
response *resty.Response
)
if api == nil {
return nil, fmt.Errorf("api config nil")
}
if len(api.Sign) > 0 {
signHandle := GetSignHandle(api.Sign)
if signHandle == nil {
return nil, fmt.Errorf("sign `%s` not supported", api.Sign)
}
if api, input, header, err = signHandle.Sign(api, input, header); err != nil {
return nil, fmt.Errorf("signature `%s` error:%s", api.Sign, err.Error())
} else {
apiNew, inputNew, headerNew = api, input, header
}
}
client := resty.New()
client.SetBaseURL(apiNew.Host)
if apiNew.Timeout > 0 {
client.SetTimeout(time.Duration(apiNew.Timeout) * time.Millisecond)
}
request := client.R()
if logger != nil {
request.EnableTrace()
defer func() {
trace := request.TraceInfo()
entry := logger.WithFields(map[string]interface{}{
"host": api.Host,
"path": api.Path,
"method": api.Method,
"content_type": api.ContentType,
"header": headerNew,
"input": inputNew,
"remote_addr": trace.RemoteAddr.String(),
"cost": trace.TotalTime / time.Duration(time.Millisecond),
})
if err != nil {
entry.Error(err.Error())
} else {
entry.WithField("response", string(response.Body()))
entry.Info("success")
}
}()
}
request.SetHeaders(apiNew.StaticHeader)
request.SetHeaders(headerNew)
for {
if api.Method == http.MethodGet {
request = request.SetQueryParams(Map2MapString(inputNew))
break
}
if api.Method == http.MethodPost {
if api.Method == contentTypeJSON {
request.SetBody(inputNew)
break
}
request.SetMultipartFormData(Map2MapString(inputNew))
}
}
response, err = request.Execute(api.Method, api.Path)
return response, err
}
func extractResponse(bytes []byte, api *ServiceAPI) *APIResponse {
if api.DisableExtract {
var data interface{}
if err := json.Unmarshal(bytes, &data); err != nil {
data = string(bytes)
}
return &APIResponse{
Code: "",
Message: "",
Data: data,
Error: false,
}
}
code := gjson.GetBytes(bytes, api.CodeKey).String()
message := gjson.GetBytes(bytes, api.MessageKey).String()
if code != api.SuccessCode {
return &APIResponse{
Code: code,
Message: message,
Data: nil,
Error: true,
}
}
data := gjson.GetBytes(bytes, api.DataKey).Value()
return &APIResponse{
Code: code,
Message: message,
Data: data,
Error: false,
}
}