-
Notifications
You must be signed in to change notification settings - Fork 42
/
client.go
379 lines (357 loc) · 9.48 KB
/
client.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
package core
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"mime/multipart"
"net/http"
"strings"
"sync"
"time"
"github.com/bububa/oceanengine/marketing-api/core/internal/debug"
"github.com/bububa/oceanengine/marketing-api/model"
"github.com/bububa/oceanengine/marketing-api/util"
)
var (
onceInit sync.Once
httpClient *http.Client
)
func defaultHttpClient() *http.Client {
onceInit.Do(func() {
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.MaxIdleConns = 100
transport.MaxConnsPerHost = 100
transport.MaxIdleConnsPerHost = 100
httpClient = &http.Client{
Transport: transport,
Timeout: time.Second * 10,
}
})
return httpClient
}
// SDKClient sdk client
type SDKClient struct {
AppID uint64
Secret string
debug bool
sandbox bool
operatorIP string
limiter RateLimiter
client *http.Client
}
// NewSDKClient 创建SDKClient
func NewSDKClient(appID uint64, secret string) *SDKClient {
return &SDKClient{
AppID: appID,
Secret: secret,
client: defaultHttpClient(),
}
}
// SetDebug 设置debug模式
func (c *SDKClient) SetDebug(debug bool) {
c.debug = debug
}
// SetHttpClient 设置http.Client
func (c *SDKClient) SetHttpClient(client *http.Client) {
c.client = client
}
// UseSandbox 启用sandbox
func (c *SDKClient) UseSandbox() {
c.sandbox = true
}
// DisableSandbox 禁用sandbox
func (c *SDKClient) DisableSandbox() {
c.sandbox = false
}
// SetOperatorIP 设置操作者IP, 支持ipv4/ipv6
func (c *SDKClient) SetOperatorIP(ip string) {
c.operatorIP = ip
}
// SetRateLimiter 设置限流
func (c *SDKClient) SetRateLimiter(limiter RateLimiter) {
c.limiter = limiter
}
// Copy 复制SDKClient
func (c *SDKClient) Copy() *SDKClient {
return &SDKClient{
AppID: c.AppID,
Secret: c.Secret,
debug: c.debug,
sandbox: c.sandbox,
operatorIP: c.operatorIP,
client: c.client,
}
}
// Post post api
func (c *SDKClient) Post(gw string, req model.PostRequest, resp model.Response, accessToken string) error {
var reqBytes []byte
if req != nil {
reqBytes = req.Encode()
}
reqUrl := util.StringsJoin(BASE_URL, gw)
httpReq, err := http.NewRequest("POST", reqUrl, bytes.NewReader(reqBytes))
if err != nil {
return err
}
httpReq.Header.Add("Content-Type", "application/json")
if accessToken != "" {
httpReq.Header.Add("Access-Token", accessToken)
}
if c.operatorIP != "" {
httpReq.Header.Add("Operator-Ip", c.operatorIP)
}
if c.sandbox {
httpReq.Header.Add("X-Debug-Mode", "1")
}
if c.limiter != nil {
c.limiter.Take()
}
debug.PrintJSONRequest("POST", reqUrl, httpReq.Header, reqBytes, c.debug)
return c.fetch(httpReq, resp)
}
// Get get api
func (c *SDKClient) Get(gw string, req model.GetRequest, resp model.Response, accessToken string) error {
reqUrl := util.StringsJoin(BASE_URL, gw)
if req != nil {
reqUrl = util.StringsJoin(reqUrl, "?", req.Encode())
}
debug.PrintGetRequest(reqUrl, c.debug)
httpReq, err := http.NewRequest("GET", reqUrl, nil)
if err != nil {
return err
}
if accessToken != "" {
httpReq.Header.Add("Access-Token", accessToken)
}
if c.operatorIP != "" {
httpReq.Header.Add("Operator-Ip", c.operatorIP)
}
if c.sandbox {
httpReq.Header.Add("X-Debug-Mode", "1")
}
if c.limiter != nil {
c.limiter.Take()
}
return c.fetch(httpReq, resp)
}
// GetBytes get bytes api
func (c *SDKClient) GetBytes(gw string, req model.GetRequest, accessToken string) ([]byte, error) {
reqUrl := util.StringsJoin(BASE_URL, gw)
if req != nil {
reqUrl = util.StringsJoin(reqUrl, "?", req.Encode())
}
debug.PrintGetRequest(reqUrl, c.debug)
httpReq, err := http.NewRequest("GET", reqUrl, nil)
if err != nil {
return nil, err
}
if accessToken != "" {
httpReq.Header.Add("Access-Token", accessToken)
}
if c.operatorIP != "" {
httpReq.Header.Add("Operator-Ip", c.operatorIP)
}
if c.sandbox {
httpReq.Header.Add("X-Debug-Mode", "1")
}
if c.limiter != nil {
c.limiter.Take()
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return nil, err
}
defer httpResp.Body.Close()
return io.ReadAll(httpResp.Body)
}
// Upload multipart/form-data post
func (c *SDKClient) Upload(gw string, req model.UploadRequest, resp model.Response, accessToken string) error {
buf := util.GetBufferPool()
defer util.PutBufferPool(buf)
mw := multipart.NewWriter(buf)
params := req.Encode()
mp := make(map[string]string, len(params))
for _, v := range params {
var (
fw io.Writer
r io.Reader
err error
)
if v.Reader != nil {
if fw, err = mw.CreateFormFile(v.Key, v.Value); err != nil {
return err
}
r = v.Reader
builder := util.GetStringsBuilder()
builder.WriteString("@")
builder.WriteString(v.Value)
mp[v.Key] = builder.String()
util.PutStringsBuilder(builder)
} else {
if fw, err = mw.CreateFormField(v.Key); err != nil {
return err
}
r = strings.NewReader(v.Value)
mp[v.Key] = v.Value
}
if _, err = io.Copy(fw, r); err != nil {
return err
}
}
mw.Close()
reqUrl := util.StringsJoin(BASE_URL, gw)
debug.PrintPostMultipartRequest(reqUrl, mp, c.debug)
httpReq, err := http.NewRequest("POST", reqUrl, buf)
if err != nil {
return err
}
httpReq.Header.Add("Content-Type", mw.FormDataContentType())
if accessToken != "" {
httpReq.Header.Add("Access-Token", accessToken)
}
if c.operatorIP != "" {
httpReq.Header.Add("Operator-Ip", c.operatorIP)
}
if c.sandbox {
httpReq.Header.Add("X-Debug-Mode", "1")
}
if c.limiter != nil {
c.limiter.Take()
}
return c.fetch(httpReq, resp)
}
// TrackActive 转化回传API专用
func (c *SDKClient) TrackActive(req model.TrackRequest, resp model.Response) error {
var (
reqUrl = req.RequestURI()
reqBytes = req.Encode()
)
httpReq, err := http.NewRequest("POST", reqUrl, bytes.NewReader(reqBytes))
if err != nil {
return err
}
httpReq.Header.Add("Content-Type", "application/json")
if token, err := req.Sign(httpReq, nil); err == nil {
httpReq.Header.Add("x-rs256-token", token)
}
if token := req.GetAppAccessToken(); token != "" {
httpReq.Header.Add("App-Access-Token", token)
}
if c.sandbox {
httpReq.Header.Add("X-Debug-Mode", "1")
}
debug.PrintJSONRequest("POST", reqUrl, httpReq.Header, reqBytes, c.debug)
if resp != nil {
return c.fetch(httpReq, resp)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return err
}
defer httpResp.Body.Close()
if httpResp.StatusCode != 200 {
body, err := io.ReadAll(httpResp.Body)
if err != nil {
return err
}
return model.BaseResponse{Code: httpResp.StatusCode, Message: string(body)}
}
return nil
}
// AnalyticsPost 转化回传API专用
func (c *SDKClient) AnalyticsPost(gw string, req model.ConversionRequest, resp model.Response) error {
reqBytes := req.Encode()
reqUrl := util.StringsJoin(ANALYTICS_URL, gw)
httpReq, err := http.NewRequest("POST", reqUrl, bytes.NewReader(reqBytes))
if err != nil {
return err
}
httpReq.Header.Add("Content-Type", "application/json")
if token := req.GetAppAccessToken(); token != "" {
httpReq.Header.Add("App-Access-Token", token)
}
if token, err := req.Sign(httpReq, reqBytes); err == nil {
httpReq.Header.Add("x-rs256-token", token)
} else {
reqBuf := util.GetBufferPool()
reqBuf.Grow(len(reqBytes) + len(c.Secret))
reqBuf.Write(reqBytes)
reqBuf.WriteString(c.Secret)
sha256Sum := sha256.Sum256(reqBuf.Bytes())
util.PutBufferPool(reqBuf)
sign := hex.EncodeToString(sha256Sum[:])
httpReq.Header.Add("x-signature", sign)
}
if c.sandbox {
httpReq.Header.Add("X-Debug-Mode", "1")
}
debug.PrintJSONRequest("POST", reqUrl, httpReq.Header, reqBytes, c.debug)
return c.fetch(httpReq, resp)
}
// AnalyticsV1Post 电话转化回传API专用
func (c *SDKClient) AnalyticsV1Post(gw string, req model.PostRequest, resp model.Response) error {
reqBytes := req.Encode()
reqUrl := util.StringsJoin(ANALYTICSV1_URL, gw)
httpReq, err := http.NewRequest("POST", reqUrl, bytes.NewReader(reqBytes))
if err != nil {
return err
}
httpReq.Header.Add("Content-Type", "application/json")
reqBuf := util.GetBufferPool()
reqBuf.Grow(len(reqBytes) + len(c.Secret))
reqBuf.Write(reqBytes)
reqBuf.WriteString(c.Secret)
sha256Sum := sha256.Sum256(reqBuf.Bytes())
util.PutBufferPool(reqBuf)
sign := hex.EncodeToString(sha256Sum[:])
httpReq.Header.Add("x-signature", sign)
if c.sandbox {
httpReq.Header.Add("X-Debug-Mode", "1")
}
debug.PrintJSONRequest("POST", reqUrl, httpReq.Header, reqBytes, c.debug)
return c.fetch(httpReq, resp)
}
// OpenGet get api
func (c *SDKClient) OpenGet(gw string, req model.GetRequest, resp model.Response, accessToken string) error {
reqUrl := util.StringsJoin(OPEN_URL, gw)
if req != nil {
reqUrl = util.StringsJoin(reqUrl, "?", req.Encode())
}
debug.PrintGetRequest(reqUrl, c.debug)
httpReq, err := http.NewRequest("GET", reqUrl, nil)
if err != nil {
return err
}
httpReq.Header.Add("Content-Type", "application/json")
if accessToken != "" {
httpReq.Header.Add("App-Access-Token", accessToken)
}
if c.sandbox {
httpReq.Header.Add("X-Debug-Mode", "1")
}
return c.fetch(httpReq, resp)
}
// fetch execute http request
func (c *SDKClient) fetch(httpReq *http.Request, resp model.Response) error {
httpResp, err := c.client.Do(httpReq)
if err != nil {
return err
}
defer httpResp.Body.Close()
if resp == nil {
resp = &model.BaseResponse{}
}
if body, err := debug.DecodeJSONHttpResponse(httpResp.Body, resp, c.debug); err != nil {
debug.PrintError(err, c.debug)
return errors.Join(err, model.BaseResponse{
Code: httpResp.StatusCode,
Message: string(body),
})
}
if resp.IsError() {
return resp
}
return nil
}