-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_base.go
250 lines (216 loc) · 5.92 KB
/
api_base.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
package polysdk
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"github.com/quanxiang-cloud/go-polysdk/internal/hash"
"github.com/quanxiang-cloud/go-polysdk/internal/polysign"
"github.com/quanxiang-cloud/go-polysdk/internal/signature"
)
// header define
const (
HeaderContentType = "Content-Type"
HeaderXRequestID = "X-Request_id"
)
// Header exports
type Header = http.Header
// http method exports
const (
MethodGet = http.MethodGet
MethodHead = http.MethodHead
MethodPost = http.MethodPost
MethodPut = http.MethodPut
MethodPatch = http.MethodPatch
MethodDelete = http.MethodDelete
MethodConnect = http.MethodConnect
MethodOptions = http.MethodOptions
MethodTrace = http.MethodTrace
)
// Content-Type MIME of the most common data formats.
const (
MIMEJSON = "application/json"
MIMEHTML = "text/html"
MIMEXML = "application/xml"
MIMEXML2 = "text/xml"
MIMEPlain = "text/plain"
MIMEPOSTForm = "application/x-www-form-urlencoded"
MIMEMultipartPOSTForm = "multipart/form-data"
MIMEPROTOBUF = "application/x-protobuf"
MIMEMSGPACK = "application/x-msgpack"
MIMEMSGPACK2 = "application/msgpack"
MIMEYAML = "application/x-yaml"
)
// BodyBase is base struct of body
type BodyBase struct {
// NOTE: path and other hide parameter
PolyHide map[string]interface{} `json:"$polyapi_hide$,omitempty"`
// NOTE: none-object customer body root
CustomerBody interface{} `json:"$body$,omitempty"`
}
// HTTPResponse is the response of http request
type HTTPResponse struct {
StatusCode int
Status string
Body json.RawMessage
Header Header
}
// DoRequestAPI is the custom api for access apis from polyapi
func (c *PolyClient) DoRequestAPI(apiPath string, method string, header Header, body interface{}) (*HTTPResponse, error) {
bodyBytes, err := c.GenHeaderSignature(header, body)
if err != nil {
return nil, err
}
resp, err := c.HTTPRequest(c.remoteURL+apiPath, method, header, bodyBytes)
if err != nil {
return nil, err
}
var respBody []byte
if resp.StatusCode == http.StatusOK {
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
resp.Body.Close()
respBody = b
} else {
respBody = []byte(fmt.Sprintf(`%q`, resp.Status))
}
r := &HTTPResponse{
Body: respBody,
Header: resp.Header,
Status: resp.Status,
StatusCode: resp.StatusCode,
}
return r, nil
}
// CustomBody is custom body
type CustomBody map[string]interface{}
// Add insert a new field to custom body
func (b CustomBody) Add(name string, data interface{}) bool {
return b.add(name, data, false)
}
// Set insert a new field to custom body forced
func (b CustomBody) Set(name string, data interface{}) bool {
return b.add(name, data, true)
}
func (b CustomBody) add(name string, data interface{}, force bool) bool {
if _, ok := b[name]; ok && !force {
return false
}
b[name] = data
return true
}
// NewCustomBody generate a custom body with signature
func (c *PolyClient) NewCustomBody() CustomBody {
return CustomBody{}
}
// MakeBodyBase create a BodyBase with signature
func (c *PolyClient) MakeBodyBase() BodyBase {
return BodyBase{}
}
// HTTPRequest do a custom http request
func (c *PolyClient) HTTPRequest(reqURL, method string, header Header, data []byte) (*http.Response, error) {
if err := validateHTTPMethod(method); err != nil {
return nil, err
}
uri, err := url.Parse(reqURL)
if err != nil {
return nil, err
}
var reader io.Reader
if method == MethodGet { // data to query if method is 'GET'
uri.RawQuery, err = signature.ToQuery(data)
if err != nil {
return nil, err
}
} else {
reader = bytes.NewReader(data)
}
req, err := http.NewRequest(method, uri.String(), reader)
if err != nil {
return nil, err
}
req.Header = header
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}
//------------------------------------------------------------------------------
// GenHeaderSignature create header.Signature form body and return body bytes
func (c *PolyClient) GenHeaderSignature(header Header, body interface{}) ([]byte, error) {
var b []byte
var err error
switch d := body.(type) {
case json.RawMessage:
b = []byte(d)
case []byte:
b = d
default:
if b, err = json.Marshal(body); err != nil {
return nil, err
}
}
header.Set(HeaderXRequestID, hash.ShortID(0))
var signInfo CustomBody
if err := json.Unmarshal(b, &signInfo); err != nil {
return nil, err
}
var (
signVals = [][2]string{
{polysign.XHeaderPolySignKeyID, c.accessKeyID},
{polysign.XHeaderPolySignMethod, polysign.XHeaderPolySignMethodVal},
{polysign.XHeaderPolySignVersion, polysign.XHeaderPolySignVersionVal},
{polysign.XHeaderPolySignTimestamp, c.polyTimestamp()},
}
opSignVals = func(fn func(string, string) error) error {
for _, v := range signVals {
if err := fn(v[0], v[1]); err != nil {
return err
}
}
return nil
}
opAddBodyHeader = func(name, val string) error {
if name != polysign.XBodyPolySignSignature {
header.Set(name, val)
}
if !signInfo.Add(name, val) {
err = fmt.Errorf("duplicate field %s in body", name)
return err
}
return nil
}
opDelBody = func(name, val string) error {
delete(signInfo, name)
return nil
}
)
if err := opSignVals(opAddBodyHeader); err != nil {
return nil, err
}
signature, err := c.sign.Signature(signInfo)
if err != nil {
return nil, err
}
if err := opAddBodyHeader(polysign.XBodyPolySignSignature, signature); err != nil {
return nil, err
}
if err := opSignVals(opDelBody); err != nil {
return nil, err
}
return json.Marshal(signInfo)
}
func validateHTTPMethod(method string) error {
switch method {
case MethodGet, MethodHead, MethodPost,
MethodPut, MethodPatch, MethodDelete,
MethodConnect, MethodOptions, MethodTrace:
return nil
}
return fmt.Errorf("unsupport http method '%s'", method)
}