-
Notifications
You must be signed in to change notification settings - Fork 174
/
baseClient.go
546 lines (459 loc) · 13.1 KB
/
baseClient.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
package kernel
import (
"bytes"
"context"
"errors"
"fmt"
"github.com/ArtisanCloud/PowerLibs/v3/http/contract"
"github.com/ArtisanCloud/PowerLibs/v3/http/helper"
contract2 "github.com/ArtisanCloud/PowerLibs/v3/logger/contract"
"github.com/ArtisanCloud/PowerLibs/v3/object"
"github.com/ArtisanCloud/PowerLibs/v3/os"
"github.com/ArtisanCloud/PowerWeChat/v3/src/kernel/power"
request2 "github.com/ArtisanCloud/PowerWeChat/v3/src/kernel/request"
response2 "github.com/ArtisanCloud/PowerWeChat/v3/src/kernel/response"
"github.com/ArtisanCloud/PowerWeChat/v3/src/kernel/support"
"io"
"io/ioutil"
"net/http"
"strconv"
)
type BaseClient struct {
HttpHelper *helper.RequestHelper
BaseURI string
QueryRaw bool
*support.ResponseCastable
Signer *support.SHA256WithRSASigner
App *ApplicationInterface
Token *AccessToken
GetMiddlewareOfAccessToken contract.RequestMiddleware
GetMiddlewareOfLog func(logger contract2.LoggerInterface) contract.RequestMiddleware
GetMiddlewareOfRefreshAccessToken func(retry int) contract.RequestMiddleware
}
type UploadForm struct {
FileName string
Contents []*UploadContent
}
type UploadContent struct {
Name string
Value interface{}
}
func NewBaseClient(app *ApplicationInterface, token *AccessToken) (*BaseClient, error) {
config := (*app).GetConfig()
baseURI := config.GetString("http.base_uri", "/")
if token == nil {
token = (*app).GetAccessToken()
}
h, err := helper.NewRequestHelper(&helper.Config{
BaseUrl: baseURI,
})
if err != nil {
return nil, err
}
client := &BaseClient{
HttpHelper: h,
App: app,
Token: token,
}
// to be setup middleware here
client.OverrideGetMiddlewares()
client.RegisterHttpMiddlewares()
mchID := config.GetString("mch_id", "")
serialNO := config.GetString("serial_no", "")
keyPath := config.GetString("key_path", "")
if mchID != "" && serialNO != "" && keyPath != "" {
client.Signer = &support.SHA256WithRSASigner{
MchID: mchID,
CertificateSerialNo: serialNO,
PrivateKeyPath: keyPath,
}
}
return client, nil
}
func (client *BaseClient) HttpGet(ctx context.Context, url string, query *object.StringMap, outHeader interface{}, outBody interface{}) (interface{}, error) {
return client.Request(
ctx,
url,
http.MethodGet,
&object.HashMap{
"query": query,
},
false,
outHeader,
outBody,
)
}
func (client *BaseClient) HttpPost(ctx context.Context, url string, data interface{}, outHeader interface{}, outBody interface{}) (interface{}, error) {
return client.Request(
ctx,
url,
http.MethodPost,
&object.HashMap{
"form_params": data,
},
false,
outHeader,
outBody,
)
}
func (client *BaseClient) HttpPostJson(ctx context.Context, url string, data interface{}, query *object.StringMap, outHeader interface{}, outBody interface{}) (interface{}, error) {
return client.Request(
ctx,
url,
http.MethodPost,
&object.HashMap{
"query": query,
"form_params": data,
},
false,
outHeader,
outBody,
)
}
func (client *BaseClient) HttpPostJsonByEncode(ctx context.Context, url string, data interface{}, query *object.StringMap, outHeader interface{}, outBody interface{}) (interface{}, error) {
return client.RequestByEncodedData(
ctx,
url,
http.MethodPost,
&object.HashMap{
"query": query,
"form_params": data,
},
false,
outHeader,
outBody,
)
}
func (client *BaseClient) HttpUpload(ctx context.Context, url string, files *object.HashMap, form *UploadForm, query interface{}, outHeader interface{}, outBody interface{}) (interface{}, error) {
// http client request
df := client.HttpHelper.Df().WithContext(ctx).Uri(url).Method(http.MethodPost)
var mems map[string]io.Reader
// 遍历表单的数据
if form != nil {
mems = make(map[string]io.Reader)
for _, content := range form.Contents {
value, err := os.ConvertFileHandleToReader(content.Value)
if err != nil {
return nil, err
}
mems[content.Name] = value
}
}
df.Multipart(func(multipart contract.MultipartDfInterface) {
// 遍历文件目录
if files != nil {
for name, path := range *files {
multipart.FileByPath(name, path.(string))
}
}
for k, v := range mems {
multipart.FileMem(form.FileName, k, v)
}
})
// set query params
if query != nil {
queries := query.(*object.StringMap)
if queries != nil {
for k, v := range *queries {
df.Query(k, v)
}
}
}
// set debug mode
config := (*client.App).GetConfig()
// 微信如果需要传debug模式
debug := config.GetBool("debug", false)
if debug {
df.Query("debug", "1")
}
response, err := df.Request()
if err != nil {
return response, err
}
// decode response body to outBody
if outBody != nil {
err = client.HttpHelper.ParseResponseBodyContent(response, outBody)
if err != nil {
return nil, err
}
}
return response, err
}
func (client *BaseClient) Request(ctx context.Context, url string, method string, options *object.HashMap,
returnRaw bool, outHeader interface{}, outBody interface{},
) (*http.Response, error) {
// http client request
client.QueryRaw = returnRaw
df := client.HttpHelper.Df().WithContext(ctx).Uri(url).Method(method)
// 检查是否需要有请求参数配置
if options != nil {
// set query key values
if (*options)["query"] != nil {
queries := (*options)["query"].(*object.StringMap)
if queries != nil {
for k, v := range *queries {
df.Query(k, v)
}
}
}
config := (*client.App).GetConfig()
// 微信如果需要传debug模式
debug := config.GetBool("debug", false)
if debug {
df.Query("debug", "1")
}
// set body json
if (*options)["form_params"] != nil {
df.Json((*options)["form_params"])
}
}
ctxQuery := ctx.Value("query")
if ctxQuery != nil {
queries := ctxQuery.(*object.StringMap)
if queries != nil {
for k, v := range *queries {
df.Query(k, v)
}
}
}
response, err := df.Request()
if err != nil {
return response, err
}
// decode response body to outBody
if outBody != nil {
err = client.HttpHelper.ParseResponseBodyContent(response, outBody)
if err != nil {
return nil, err
}
}
// decode response header to outHeader
if outHeader != nil {
strHeader, err := object.JsonEncode(response.Header)
if err != nil {
return nil, err
}
err = object.JsonDecode([]byte(strHeader), outHeader)
if err != nil {
return nil, err
}
}
return response, err
}
func (client *BaseClient) RequestByEncodedData(ctx context.Context, url string, method string, options *object.HashMap,
returnRaw bool, outHeader interface{}, outBody interface{},
) (*http.Response, error) {
// http client request
client.QueryRaw = returnRaw
df := client.HttpHelper.Df().WithContext(ctx).Uri(url).Method(method)
// 检查是否需要有请求参数配置
if options != nil {
// set query key values
if (*options)["query"] != nil {
queries := (*options)["query"].(*object.StringMap)
if queries != nil {
for k, v := range *queries {
df.Query(k, v)
}
}
}
config := (*client.App).GetConfig()
// 微信如果需要传debug模式
debug := config.GetBool("debug", false)
if debug {
df.Query("debug", "1")
}
// set body json
if (*options)["form_params"] != nil {
body := &power.JsonEncoder{
Data: (*options)["form_params"],
}
df.Any(body)
}
}
ctxQuery := ctx.Value("query")
if ctxQuery != nil {
queries := ctxQuery.(*object.StringMap)
if queries != nil {
for k, v := range *queries {
df.Query(k, v)
}
}
}
response, err := df.Request()
if err != nil {
return response, err
}
// decode response body to outBody
if outBody != nil {
err = client.HttpHelper.ParseResponseBodyContent(response, outBody)
if err != nil {
return nil, err
}
}
// decode response header to outHeader
if outHeader != nil {
strHeader, err := object.JsonEncode(response.Header)
if err != nil {
return nil, err
}
err = object.JsonDecode([]byte(strHeader), outHeader)
if err != nil {
return nil, err
}
}
return response, err
}
func (client *BaseClient) RequestRaw(ctx context.Context, url string, method string, options *object.HashMap, outHeader interface{}, outBody interface{}) (*http.Response, error) {
return client.Request(ctx, url, method, options, true, outHeader, outBody)
}
func (client *BaseClient) RegisterHttpMiddlewares() {
// access token
accessTokenMiddleware := client.GetMiddlewareOfAccessToken
// log
logMiddleware := client.GetMiddlewareOfLog
// check invalid access token
checkAccessTokenMiddleware := client.GetMiddlewareOfRefreshAccessToken
config := (*client.App).GetConfig()
logger := (*client.App).GetComponent("Logger").(contract2.LoggerInterface)
client.HttpHelper.WithMiddleware(
accessTokenMiddleware,
logMiddleware(logger),
checkAccessTokenMiddleware(3),
helper.HttpDebugMiddleware(config.GetBool("http_debug", false)),
)
}
// ----------------------------------------------------------------------
func (client *BaseClient) OverrideGetMiddlewares() {
client.OverrideGetMiddlewareOfLog()
client.OverrideGetMiddlewareOfAccessToken()
client.OverrideGetMiddlewareOfRefreshAccessToken()
}
func (client *BaseClient) OverrideGetMiddlewareOfAccessToken() {
client.GetMiddlewareOfAccessToken = func(handle contract.RequestHandle) contract.RequestHandle {
return func(request *http.Request) (response *http.Response, err error) {
// 前置中间件
//fmt.Println("获取access token, 在请求前执行")
accessToken := (*client.App).GetAccessToken()
if accessToken != nil {
config := (*client.App).GetContainer().Config
request, err = accessToken.ApplyToRequest(request, config)
}
if err != nil {
return nil, err
}
response, err = handle(request)
if err != nil {
return response, err
}
// handle 执行之后就可以操作 response 和 err
// 后置中间件
//fmt.Println("获取access token, 在请求后执行")
return
}
}
}
func (client *BaseClient) OverrideGetMiddlewareOfLog() {
client.GetMiddlewareOfLog = func(logger contract2.LoggerInterface) contract.RequestMiddleware {
return contract.RequestMiddleware(func(handle contract.RequestHandle) contract.RequestHandle {
return func(request *http.Request) (response *http.Response, err error) {
// 前置中间件
request2.LogRequest(logger, request)
response, err = handle(request)
if err != nil {
return response, err
}
// 后置中间件
response2.LogResponse(logger, response)
return
}
})
}
}
func (client *BaseClient) OverrideGetMiddlewareOfRefreshAccessToken() {
client.GetMiddlewareOfRefreshAccessToken = func(retry int) contract.RequestMiddleware {
return contract.RequestMiddleware(func(handle contract.RequestHandle) contract.RequestHandle {
return func(request *http.Request) (response *http.Response, err error) {
// 前置中间件
//fmt.Println("检查微信返回错误,token是否失效,执行前访问")
response, err = handle(request)
// handle 执行之后就可以操作 response 和 err
if err != nil {
return response, err
}
if response.StatusCode != http.StatusOK {
return response, errors.New(fmt.Sprintf("http response code:%d", response.StatusCode))
}
if !client.QueryRaw {
rs, err := client.CheckTokenNeedRefresh(request, response, retry)
if err != nil {
return rs, err
} else if rs != nil {
return rs, nil
}
}
// 后置中间件
//fmt.Println("检查微信返回错误,token是否失效,, 在请求后执行")
return
}
})
}
}
func (client *BaseClient) CheckTokenNeedRefresh(req *http.Request, rs *http.Response, retry int) (*http.Response, error) {
mapResponse := &object.HashMap{}
err := client.HttpHelper.ParseResponseBodyToMap(rs, mapResponse)
if err != nil {
return nil, err
}
errCode := 0
if (*mapResponse)["errcode"] != nil {
switch (*mapResponse)["errcode"].(type) {
case float64:
errCode = int((*mapResponse)["errcode"].(float64))
case int:
errCode = (*mapResponse)["errcode"].(int)
case string:
errCode, err = strconv.Atoi((*mapResponse)["errcode"].(string))
default:
}
conditions := &object.HashMap{
"code": errCode,
}
if retry > 0 && client.RetryDecider(conditions) {
client.Token.Refresh()
// clone 一个request
token, err := client.Token.GetToken(false)
q := req.URL.Query()
q.Set(client.Token.TokenKey, token.AccessToken)
req.URL.RawQuery = q.Encode()
req2 := req.Clone(req.Context())
if req.Body != nil {
// 缓存请求body
reqData, err := ioutil.ReadAll(req.Body)
if err != nil {
return nil, err
}
// 给两个request复制缓存下来的body数据
req.Body = ioutil.NopCloser(bytes.NewBuffer(reqData))
req2.Body = ioutil.NopCloser(bytes.NewReader(reqData))
}
res2, err := client.HttpHelper.GetClient().DoRequest(req2)
if err != nil {
return nil, err
}
return res2, err
//b, err := ioutil.ReadAll(res2.Body)
//rs.Body = ioutil.NopCloser(bytes.NewBuffer(b))
//content := string(b)
//fmt2.Dump(content)
}
}
return rs, nil
}
func (client *BaseClient) RetryDecider(conditions *object.HashMap) bool {
code := (*conditions)["code"].(int)
if code == 40001 || code == 40014 || code == 42001 {
return true
}
return false
}