-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathclient.go
More file actions
755 lines (667 loc) · 17.5 KB
/
Copy pathclient.go
File metadata and controls
755 lines (667 loc) · 17.5 KB
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
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
Logger Logger
CacheConfig *CacheConfig
}
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{}
settled bool
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
DisableDecompression bool
ValidateStatus func(int) bool
InterceptorOptions InterceptorOptions
Proxy *Proxy
OnUploadProgress func(bytesRead, totalBytes int64)
OnDownloadProgress func(bytesRead, totalBytes int64)
LogLevel LogLevel
Cache *RequestCacheOptions
}
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{}, Logger: NewLogger(LevelNone)}
func (r *Response) JSON(v interface{}) error {
return json.Unmarshal(r.Body, v)
}
func (p *Promise) Then(fn func(*Response)) *Promise {
p.mu.Lock()
if p.settled && p.err == nil {
response := p.response
p.mu.Unlock()
fn(response)
} else {
if !p.settled {
p.then = fn
}
p.mu.Unlock()
}
return p
}
func (p *Promise) Catch(fn func(error)) *Promise {
p.mu.Lock()
if p.settled && p.err != nil {
err := p.err
p.mu.Unlock()
fn(err)
} else {
if !p.settled {
p.catch = fn
}
p.mu.Unlock()
}
return p
}
func (p *Promise) Finally(fn func()) {
p.mu.Lock()
if p.settled {
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()
if p.settled {
p.mu.Unlock()
return
}
p.response = resp
p.err = err
p.settled = true
thenFn := p.then
catchFn := p.catch
finallyFn := p.finally
p.mu.Unlock()
if thenFn != nil && err == nil {
thenFn(resp)
}
if catchFn != nil && err != nil {
catchFn(err)
}
if finallyFn != nil {
finallyFn()
}
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 {
promise := NewPromise()
go func() {
resp, err := Request(method, urlStr, options...)
promise.resolve(resp, err)
}()
return promise
}
func (c *Client) Request(options *RequestOptions) (*Response, error) {
if options == nil {
return nil, errors.New("request options must not be nil")
}
if options.Timeout == 0 {
options.Timeout = 1000
}
if options.MaxContentLength == 0 {
options.MaxContentLength = 2000
}
if options.MaxBodyLength == 0 {
options.MaxBodyLength = 2000
}
if options.ResponseType == "" {
options.ResponseType = "json"
}
if options.ResponseEncoding == "" {
options.ResponseEncoding = "utf8"
}
if options.MaxRedirects == 0 {
options.MaxRedirects = 21
}
if options.Method == "" {
options.Method = "GET"
}
if options.DisableDecompression {
options.Decompress = false
} else if !options.Decompress {
// Decompression historically defaulted to true. The separate disable
// option makes that default explicit without changing existing callers.
options.Decompress = true
}
validMethods := map[string]bool{
"GET": true,
"POST": true,
"PUT": true,
"DELETE": true,
"PATCH": true,
"HEAD": true,
"OPTIONS": true,
}
upperMethod := strings.ToUpper(options.Method)
if !validMethods[upperMethod] {
return nil, fmt.Errorf("invalid HTTP method: %q", options.Method)
}
startTime := time.Now()
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()
}
// Cache check: try to get cached response before making request
var cacheKey string
shouldCache := shouldCacheRequest(c.CacheConfig, options)
if shouldCache && !shouldForceRefresh(options) {
cacheKey = generateCacheKey(c.CacheConfig, options, fullURL)
if cachedEntry := c.CacheConfig.Cache.Get(cacheKey); cachedEntry != nil {
// Return cached response
return &Response{
StatusCode: cachedEntry.StatusCode,
Headers: cachedEntry.Headers,
Body: cachedEntry.Body,
}, nil
}
}
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)
}
if !options.Decompress && req.Header.Get("Accept-Encoding") == "" {
// Setting an explicit encoding prevents net/http from transparently
// requesting and decompressing gzip responses.
req.Header.Set("Accept-Encoding", "identity")
}
if c.Logger != nil {
c.Logger.LogRequest(req, options.LogLevel)
}
baseHTTPClient := c.HTTPClient
if baseHTTPClient == nil {
baseHTTPClient = http.DefaultClient
}
httpClient := *baseHTTPClient
httpClient.Timeout = time.Duration(options.Timeout) * time.Millisecond
if options.MaxRedirects > 0 {
originalCheckRedirect := httpClient.CheckRedirect
httpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if len(via) >= options.MaxRedirects {
return fmt.Errorf("too many redirects (max: %d)", options.MaxRedirects)
}
if originalCheckRedirect != nil {
return originalCheckRedirect(req, via)
}
return nil
}
}
if options.Proxy != nil {
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
}
baseTransport := http.DefaultTransport
if httpClient.Transport != nil {
baseTransport = httpClient.Transport
}
transport, ok := baseTransport.(*http.Transport)
if !ok {
return nil, errors.New("proxy options require an *http.Transport")
}
transport = transport.Clone()
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},
}
}
httpClient.Transport = transport
}
resp, err := httpClient.Do(req)
if err != nil {
if c.Logger != nil {
c.Logger.LogError(err, options.LogLevel)
}
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
limitedReader := io.LimitReader(resp.Body, options.MaxContentLength+1)
if options.OnDownloadProgress != nil {
buf := &bytes.Buffer{}
progressWriter := &ProgressWriter{
writer: buf,
total: resp.ContentLength,
onProgress: options.OnDownloadProgress,
}
_, err = io.Copy(progressWriter, limitedReader)
if err != nil {
return nil, err
}
responseBody = buf.Bytes()
} else {
responseBody, err = io.ReadAll(limitedReader)
if err != nil {
return nil, err
}
}
if int64(len(responseBody)) > options.MaxContentLength {
return nil, errors.New("response content length exceeded maxContentLength")
}
duration := time.Since(startTime)
if c.Logger != nil {
c.Logger.LogResponse(resp, responseBody, duration, options.LogLevel)
}
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)
}
}
// Cache store: save successful response to cache
if shouldCache && resp.StatusCode >= 200 && resp.StatusCode < 300 {
ttl := getCacheTTL(c.CacheConfig, options)
if ttl > 0 {
if cacheKey == "" {
cacheKey = generateCacheKey(c.CacheConfig, options, fullURL)
}
c.CacheConfig.Cache.Set(cacheKey, &CacheEntry{
Body: responseBody,
StatusCode: resp.StatusCode,
Headers: resp.Header.Clone(),
CreatedAt: time.Now(),
}, ttl)
}
}
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
}
if src.Cache != nil {
dst.Cache = src.Cache
}
if src.Decompress {
dst.Decompress = true
}
dst.DisableDecompression = src.DisableDecompression
}
func SetBaseURL(baseURL string) {
defaultClient.BaseURL = baseURL
}
func NewClient(baseURL string) *Client {
return &Client{
BaseURL: baseURL,
HTTPClient: &http.Client{},
Logger: NewLogger(LevelNone),
}
}
// NewClientWithCache creates a client with cache enabled
func NewClientWithCache(baseURL string, cacheConfig *CacheConfig) *Client {
return &Client{
BaseURL: baseURL,
HTTPClient: &http.Client{},
Logger: NewLogger(LevelNone),
CacheConfig: cacheConfig,
}
}
// SetCache sets the cache configuration for the client
func (c *Client) SetCache(config *CacheConfig) {
c.CacheConfig = config
}
// ClearCache clears all entries in the client's cache
func (c *Client) ClearCache() {
if c.CacheConfig != nil && c.CacheConfig.Cache != nil {
c.CacheConfig.Cache.Clear()
}
}
// CacheStats returns the cache statistics
func (c *Client) CacheStats() *CacheStats {
if c.CacheConfig != nil && c.CacheConfig.Cache != nil {
stats := c.CacheConfig.Cache.Stats()
return &stats
}
return nil
}