-
Notifications
You must be signed in to change notification settings - Fork 0
/
csb.go
220 lines (187 loc) · 5.24 KB
/
csb.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
package csb
import (
"context"
"errors"
"fmt"
"io"
"net/url"
"strconv"
"strings"
"time"
"github.com/imroc/req/v3"
)
// CSBClient CSBClient
type CSBClient struct {
url string // csb地址
accessKey string // ak
secretKey string // sk
ApiName string // 接口名称
ApiMethod string // 接口请求方法
ApiVersion string // 接口版本
ContentType string // 请求的content-type
Headers map[string]string // 请求头
QueryParam map[string]string // query参数
FormParam map[string]string // 表单数据
Body []byte // 请求体,文件、表单、JSON等
client *req.Client
}
const (
apiNameKey = "_api_name"
apiVersionKey = "_api_version"
accessKey = "_api_access_key"
secretKey = "_api_secret_key"
signatureKey = "_api_signature"
timestampKey = "_api_timestamp"
defaultUserAgent = "csbBroker"
)
// NewCSBClient 返回新的CSB客户端
func NewCSBClient(url, accessKey, secretKey string) *CSBClient {
client := req.C().SetBaseURL(url).OnBeforeRequest(func(c *req.Client, r *req.Request) error {
if r.RetryAttempt > 0 { // Ignore on retry.
return nil
}
return nil
})
return &CSBClient{
client: client,
url: url,
accessKey: accessKey,
secretKey: secretKey,
}
}
// SetApiName 设置请求接口的名称
func (c *CSBClient) SetApiName(apiName string) *CSBClient {
c.ApiName = apiName
return c
}
// SetApiMethod 设置请求接口的方法,只支持get或post
func (c *CSBClient) SetApiMethod(apiMethod string) *CSBClient {
c.ApiMethod = apiMethod
return c
}
// SetApiVersion 设置请求接口的版本
func (c *CSBClient) SetApiVersion(apiVersion string) *CSBClient {
c.ApiVersion = apiVersion
return c
}
// SetContentType 设置请求content-type
func (c *CSBClient) SetContentType(contentType string) *CSBClient {
c.ContentType = contentType
return c
}
// SetHeaders 设置请求头
func (c *CSBClient) SetHeaders(headers map[string]string) *CSBClient {
c.Headers = headers
return c
}
// SetQueryParam 设置query参数对
func (c *CSBClient) SetQueryParam(queryParam map[string]string) *CSBClient {
c.QueryParam = queryParam
return c
}
// SetFormParam 设置表单数据
func (c *CSBClient) SetFormParam(formParam map[string]string) *CSBClient {
c.FormParam = formParam
return c
}
// SetBody 设置请求体
func (c *CSBClient) SetBody(body []byte) *CSBClient {
c.Body = body
return c
}
// Do 执行请求
func (c *CSBClient) Do(ctx context.Context, result interface{}) (*req.Response, error) {
// 参数验证
if err := c.validate(); err != nil {
return nil, err
}
// 表单数据设置
formData := url.Values{}
if c.FormParam != nil {
for k, v := range c.FormParam {
formData.Set(k, v)
}
}
// merge body
requestBody := c.Body
if c.Body == nil {
requestBody = []byte(formData.Encode())
}
req := c.client.R().SetContext(ctx).SetQueryParams(c.QueryParam).SetBodyBytes(requestBody)
// merge params
params := make(map[string]string)
if c.QueryParam != nil {
params = c.QueryParam
}
if c.FormParam != nil {
for k, v := range c.FormParam {
params[k] = v
}
}
// add request header
signHeaders := signParams(params, c.ApiName, c.ApiVersion, c.accessKey, c.secretKey)
if c.Headers != nil {
req.SetHeadersNonCanonical(c.Headers)
}
req.SetHeadersNonCanonical(signHeaders).SetHeader("Content-Type", c.ContentType).SetResult(result)
method := strings.ToLower(c.ApiMethod)
if method == "get" {
return req.Get("")
} else if method == "post" {
res, err := req.Post("")
if err != nil {
return res, fmt.Errorf("failed to do post request: %v", err)
}
defer res.Body.Close()
if res.StatusCode > 299 {
byteBody, err := io.ReadAll(res.Body)
if err != nil {
return res, fmt.Errorf("status code: %v, read response body failed: %v", res.StatusCode, err)
}
return res, fmt.Errorf("status code %d, body: %v", res.StatusCode, string(byteBody))
}
return res, nil
}
return nil, errors.New("only support get or post")
}
// signParams 对参数进行签名
func signParams(
params map[string]string,
api string,
version string,
ak string,
sk string,
) (headMaps map[string]string) {
headMaps = make(map[string]string)
params[apiNameKey] = api
headMaps[apiNameKey] = api
params[apiVersionKey] = version
headMaps[apiVersionKey] = version
v := time.Now().UnixNano() / 1000000
params[timestampKey] = strconv.FormatInt(v, 10)
headMaps[timestampKey] = strconv.FormatInt(v, 10)
params[accessKey] = ak
headMaps[accessKey] = ak
delete(params, secretKey)
delete(params, signatureKey)
signValue := doSign(params, sk)
headMaps[signatureKey] = signValue
return headMaps
}
// validate 验证参数
func (c *CSBClient) validate() error {
method := strings.ToLower(c.ApiMethod)
if method != "get" && method != "post" {
return errors.New("bad method, only support 'get' or 'post'")
}
if c.accessKey == "" || c.secretKey == "" {
return errors.New("bad request params, accessKey and secretKey must defined together")
}
if c.ApiName == "" || c.ApiVersion == "" {
return errors.New("bad request params, api or version not defined")
}
if c.ContentType == "" {
return errors.New("content-type must defined")
}
return nil
}