-
Notifications
You must be signed in to change notification settings - Fork 13
/
request.go
97 lines (78 loc) · 2.13 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
package mixin
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/go-resty/resty/v2"
)
var (
xRequestID = http.CanonicalHeaderKey("X-Request-ID")
xIntegrityToken = http.CanonicalHeaderKey("x-integrity-token")
)
var httpClient = resty.New().
SetHeader("Content-Type", "application/json").
SetHostURL(DefaultApiHost).
SetTimeout(10 * time.Second).
SetPreRequestHook(func(c *resty.Client, r *http.Request) error {
ctx := r.Context()
requestID := r.Header.Get(xRequestID)
if requestID == "" {
requestID = RequestIdFromContext(ctx)
r.Header.Set(xRequestID, requestID)
}
if s, ok := ctx.Value(signerKey).(Signer); ok {
token := s.SignToken(SignRequest(r), requestID, time.Minute)
r.Header.Set("Authorization", "Bearer "+token)
}
return nil
}).
OnAfterResponse(func(c *resty.Client, r *resty.Response) error {
if err := checkResponseRequestID(r); err != nil {
return err
}
if v, ok := r.Request.Context().Value(verifierKey).(Verifier); ok {
if err := v.Verify(r); err != nil {
return err
}
}
return nil
})
func checkResponseRequestID(r *resty.Response) error {
expect := r.Request.Header.Get(xRequestID)
got := r.Header().Get(xRequestID)
if expect != got {
return fmt.Errorf("%s mismatch, expect %q but got %q", xRequestID, expect, got)
}
return nil
}
func Request(ctx context.Context) *resty.Request {
return httpClient.R().SetContext(ctx)
}
func DecodeResponse(resp *resty.Response) ([]byte, error) {
var body struct {
Error *Error `json:"error,omitempty"`
Data json.RawMessage `json:"data,omitempty"`
}
if err := json.Unmarshal(resp.Body(), &body); err != nil {
if resp.IsError() {
return nil, createError(resp.StatusCode(), resp.StatusCode(), resp.Status())
}
return nil, createError(resp.StatusCode(), resp.StatusCode(), err.Error())
}
if body.Error != nil && body.Error.Code > 0 {
return nil, body.Error
}
return body.Data, nil
}
func UnmarshalResponse(resp *resty.Response, v interface{}) error {
data, err := DecodeResponse(resp)
if err != nil {
return err
}
if v != nil {
return json.Unmarshal(data, v)
}
return nil
}