-
Notifications
You must be signed in to change notification settings - Fork 5
/
client.go
585 lines (506 loc) · 13 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
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
package axios4go
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
type Client struct {
BaseURL string
HTTPClient *http.Client
}
type Response struct {
StatusCode int
Headers http.Header
Body []byte
}
type Promise struct {
response *Response
err error
then func(*Response)
catch func(error)
finally func()
done chan struct{}
mu sync.Mutex
}
type RequestInterceptors []func(*http.Request) error
type ResponseInterceptors []func(*http.Response) error
type InterceptorOptions struct {
RequestInterceptors RequestInterceptors
ResponseInterceptors ResponseInterceptors
}
type RequestOptions struct {
Method string
Url string
BaseURL string
Params map[string]string
Body interface{}
Headers map[string]string
Timeout int
Auth *Auth
ResponseType string
ResponseEncoding string
MaxRedirects int
MaxContentLength int64
MaxBodyLength int64
Decompress bool
ValidateStatus func(int) bool
InterceptorOptions InterceptorOptions
Proxy *Proxy
OnUploadProgress func(bytesRead, totalBytes int64)
OnDownloadProgress func(bytesRead, totalBytes int64)
}
type Proxy struct {
Protocol string
Host string
Port int
Auth *Auth
}
type Auth struct {
Username string
Password string
}
type ProgressReader struct {
reader io.Reader
total int64
read int64
onProgress func(bytesRead, totalBytes int64)
}
type ProgressWriter struct {
writer io.Writer
total int64
written int64
onProgress func(bytesWritten, totalBytes int64)
}
func (pr *ProgressReader) Read(p []byte) (int, error) {
n, err := pr.reader.Read(p)
pr.read += int64(n)
if pr.onProgress != nil {
pr.onProgress(pr.read, pr.total)
}
return n, err
}
func (pw *ProgressWriter) Write(p []byte) (int, error) {
n, err := pw.writer.Write(p)
pw.written += int64(n)
if pw.onProgress != nil {
pw.onProgress(pw.written, pw.total)
}
return n, err
}
var defaultClient = &Client{HTTPClient: &http.Client{}}
func (r *Response) JSON(v interface{}) error {
return json.Unmarshal(r.Body, v)
}
func (p *Promise) Then(fn func(*Response)) *Promise {
p.mu.Lock()
defer p.mu.Unlock()
if p.response != nil && p.err == nil {
fn(p.response)
} else {
p.then = fn
}
return p
}
func (p *Promise) Catch(fn func(error)) *Promise {
p.mu.Lock()
defer p.mu.Unlock()
if p.err != nil {
fn(p.err)
} else {
p.catch = fn
}
return p
}
func (p *Promise) Finally(fn func()) {
p.mu.Lock()
if p.response != nil || p.err != nil {
p.mu.Unlock()
fn()
} else {
p.finally = fn
p.mu.Unlock()
}
<-p.done
}
func NewPromise() *Promise {
return &Promise{
done: make(chan struct{}),
}
}
func (p *Promise) resolve(resp *Response, err error) {
p.mu.Lock()
defer p.mu.Unlock()
p.response = resp
p.err = err
if p.then != nil && err == nil {
p.then(resp)
}
if p.catch != nil && err != nil {
p.catch(err)
}
if p.finally != nil {
p.finally()
}
close(p.done)
}
func Get(urlStr string, options ...*RequestOptions) (*Response, error) {
return Request("GET", urlStr, options...)
}
func GetAsync(urlStr string, options ...*RequestOptions) *Promise {
promise := NewPromise()
go func() {
resp, err := Request("GET", urlStr, options...)
promise.resolve(resp, err)
}()
return promise
}
func Post(urlStr string, body interface{}, options ...*RequestOptions) (*Response, error) {
mergedOptions := mergeBodyIntoOptions(body, options)
return Request("POST", urlStr, mergedOptions)
}
func PostAsync(urlStr string, body interface{}, options ...*RequestOptions) *Promise {
mergedOptions := mergeBodyIntoOptions(body, options)
promise := NewPromise()
go func() {
resp, err := Request("POST", urlStr, mergedOptions)
promise.resolve(resp, err)
}()
return promise
}
func mergeBodyIntoOptions(body interface{}, options []*RequestOptions) *RequestOptions {
mergedOption := &RequestOptions{
Body: body,
}
if len(options) > 0 {
*mergedOption = *options[0]
mergedOption.Body = body
}
return mergedOption
}
func Put(urlStr string, body interface{}, options ...*RequestOptions) (*Response, error) {
mergedOptions := mergeBodyIntoOptions(body, options)
return Request("PUT", urlStr, mergedOptions)
}
func PutAsync(urlStr string, body interface{}, options ...*RequestOptions) *Promise {
mergedOptions := mergeBodyIntoOptions(body, options)
promise := NewPromise()
go func() {
resp, err := Request("PUT", urlStr, mergedOptions)
promise.resolve(resp, err)
}()
return promise
}
func Delete(urlStr string, options ...*RequestOptions) (*Response, error) {
return Request("DELETE", urlStr, options...)
}
func DeleteAsync(urlStr string, options ...*RequestOptions) *Promise {
promise := NewPromise()
go func() {
resp, err := Request("DELETE", urlStr, options...)
promise.resolve(resp, err)
}()
return promise
}
func Head(urlStr string, options ...*RequestOptions) (*Response, error) {
return Request("HEAD", urlStr, options...)
}
func HeadAsync(urlStr string, options ...*RequestOptions) *Promise {
promise := NewPromise()
go func() {
resp, err := Request("HEAD", urlStr, options...)
promise.resolve(resp, err)
}()
return promise
}
func Options(urlStr string, options ...*RequestOptions) (*Response, error) {
return Request("OPTIONS", urlStr, options...)
}
func OptionsAsync(urlStr string, options ...*RequestOptions) *Promise {
promise := NewPromise()
go func() {
resp, err := Request("OPTIONS", urlStr, options...)
promise.resolve(resp, err)
}()
return promise
}
func Patch(urlStr string, body interface{}, options ...*RequestOptions) (*Response, error) {
mergedOptions := mergeBodyIntoOptions(body, options)
return Request("PATCH", urlStr, mergedOptions)
}
func PatchAsync(urlStr string, body interface{}, options ...*RequestOptions) *Promise {
mergedOptions := mergeBodyIntoOptions(body, options)
promise := NewPromise()
go func() {
resp, err := Request("PATCH", urlStr, mergedOptions)
promise.resolve(resp, err)
}()
return promise
}
func Request(method, urlStr string, options ...*RequestOptions) (*Response, error) {
reqOptions := &RequestOptions{
Method: "GET",
Url: urlStr,
Timeout: 1000,
ResponseType: "json",
ResponseEncoding: "utf8",
MaxContentLength: 2000,
MaxBodyLength: 2000,
MaxRedirects: 21,
Decompress: true,
ValidateStatus: nil,
}
if len(options) > 0 && options[0] != nil {
mergeOptions(reqOptions, options[0])
}
if method != "" {
reqOptions.Method = method
}
return defaultClient.Request(reqOptions)
}
func RequestAsync(method, urlStr string, options ...*RequestOptions) *Promise {
resp, err := Request(method, urlStr, options...)
return &Promise{response: resp, err: err}
}
func (c *Client) Request(options *RequestOptions) (*Response, error) {
var fullURL string
if c.BaseURL != "" {
var err error
fullURL, err = url.JoinPath(c.BaseURL, options.Url)
if err != nil {
return nil, err
}
} else if options.BaseURL != "" {
var err error
fullURL, err = url.JoinPath(options.BaseURL, options.Url)
if err != nil {
return nil, err
}
} else {
fullURL = options.Url
}
if len(options.Params) > 0 {
parsedURL, err := url.Parse(fullURL)
if err != nil {
return nil, err
}
q := parsedURL.Query()
for k, v := range options.Params {
q.Add(k, v)
}
parsedURL.RawQuery = q.Encode()
fullURL = parsedURL.String()
}
var bodyReader io.Reader
var bodyLength int64
if options.Body != nil {
switch v := options.Body.(type) {
case string:
bodyReader = strings.NewReader(v)
bodyLength = int64(len(v))
case []byte:
bodyReader = bytes.NewReader(v)
bodyLength = int64(len(v))
default:
jsonBody, err := json.Marshal(options.Body)
if err != nil {
return nil, err
}
bodyReader = bytes.NewBuffer(jsonBody)
bodyLength = int64(len(jsonBody))
}
if options.MaxBodyLength > 0 && bodyLength > int64(options.MaxBodyLength) {
return nil, errors.New("request body length exceeded maxBodyLength")
}
if options.Body != nil && options.OnUploadProgress != nil {
bodyReader = &ProgressReader{
reader: bodyReader,
total: bodyLength,
onProgress: options.OnUploadProgress,
}
}
}
req, err := http.NewRequest(options.Method, fullURL, bodyReader)
if err != nil {
return nil, err
}
for _, interceptor := range options.InterceptorOptions.RequestInterceptors {
err = interceptor(req)
if err != nil {
return nil, fmt.Errorf("request interceptor failed: %w", err)
}
}
if options.Headers == nil {
options.Headers = make(map[string]string)
}
if options.Body != nil {
if _, exists := options.Headers["Content-Type"]; !exists {
options.Headers["Content-Type"] = "application/json"
}
}
for key, value := range options.Headers {
req.Header.Set(key, value)
}
if options.Auth != nil {
auth := options.Auth.Username + ":" + options.Auth.Password
basicAuth := base64.StdEncoding.EncodeToString([]byte(auth))
req.Header.Set("Authorization", "Basic "+basicAuth)
}
c.HTTPClient.Timeout = time.Duration(options.Timeout) * time.Millisecond
if options.MaxRedirects > 0 {
c.HTTPClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if len(via) >= options.MaxRedirects {
return http.ErrUseLastResponse
}
return nil
}
}
if options.Proxy != nil {
// support http and https
proxyStr := fmt.Sprintf("%s://%s:%d", options.Proxy.Protocol, options.Proxy.Host, options.Proxy.Port)
proxyURL, err := url.Parse(proxyStr)
if err != nil {
return nil, err
}
transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL),
}
if options.Proxy.Auth != nil {
auth := options.Proxy.Auth.Username + ":" + options.Proxy.Auth.Password
basicAuth := base64.StdEncoding.EncodeToString([]byte(auth))
transport.ProxyConnectHeader = http.Header{
"Proxy-Authorization": {"Basic " + basicAuth},
}
}
c.HTTPClient.Transport = transport
// cancel proxy after request
defer func() {
c.HTTPClient.Transport = nil
}()
}
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer func() {
if cerr := resp.Body.Close(); cerr != nil {
if err != nil {
err = fmt.Errorf("%w; failed to close response body: %v", err, cerr)
} else {
err = fmt.Errorf("failed to close response body: %v", cerr)
}
}
}()
var responseBody []byte
if options.OnDownloadProgress != nil {
buf := &bytes.Buffer{}
progressWriter := &ProgressWriter{
writer: buf,
total: resp.ContentLength,
onProgress: options.OnDownloadProgress,
}
_, err = io.Copy(progressWriter, resp.Body)
if err != nil {
return nil, err
}
responseBody = buf.Bytes()
} else {
responseBody, err = io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
}
if int64(len(responseBody)) > int64(options.MaxContentLength) {
return nil, errors.New("response content length exceeded maxContentLength")
}
if options.ValidateStatus != nil && !(options.ValidateStatus(resp.StatusCode)) {
return nil, fmt.Errorf("Request failed with status code: %v", resp.StatusCode)
}
for _, interceptor := range options.InterceptorOptions.ResponseInterceptors {
err = interceptor(resp)
if err != nil {
return nil, fmt.Errorf("response interceptor failed: %w", err)
}
}
return &Response{
StatusCode: resp.StatusCode,
Headers: resp.Header,
Body: responseBody,
}, err
}
func mergeOptions(dst, src *RequestOptions) {
if src.Method != "" {
dst.Method = src.Method
}
if src.Url != "" {
dst.Url = src.Url
}
if src.BaseURL != "" {
dst.BaseURL = src.BaseURL
}
if src.Params != nil {
dst.Params = src.Params
}
if src.Body != nil {
dst.Body = src.Body
}
if src.Headers != nil {
dst.Headers = src.Headers
}
if src.Timeout != 0 {
dst.Timeout = src.Timeout
}
if src.Auth != nil {
dst.Auth = src.Auth
}
if src.ResponseType != "" {
dst.ResponseType = src.ResponseType
}
if src.ResponseEncoding != "" {
dst.ResponseEncoding = src.ResponseEncoding
}
if src.MaxRedirects != 0 {
dst.MaxRedirects = src.MaxRedirects
}
if src.MaxContentLength != 0 {
dst.MaxContentLength = src.MaxContentLength
}
if src.MaxBodyLength != 0 {
dst.MaxBodyLength = src.MaxBodyLength
}
if src.ValidateStatus != nil {
dst.ValidateStatus = src.ValidateStatus
}
if src.InterceptorOptions.RequestInterceptors != nil {
dst.InterceptorOptions.RequestInterceptors = src.InterceptorOptions.RequestInterceptors
}
if src.InterceptorOptions.ResponseInterceptors != nil {
dst.InterceptorOptions.ResponseInterceptors = src.InterceptorOptions.ResponseInterceptors
}
if src.OnUploadProgress != nil {
dst.OnUploadProgress = src.OnUploadProgress
}
if src.OnDownloadProgress != nil {
dst.OnDownloadProgress = src.OnDownloadProgress
}
if src.Proxy != nil {
dst.Proxy = src.Proxy
}
dst.Decompress = src.Decompress
}
func SetBaseURL(baseURL string) {
defaultClient.BaseURL = baseURL
}
func NewClient(baseURL string) *Client {
return &Client{
BaseURL: baseURL,
HTTPClient: &http.Client{},
}
}