-
Notifications
You must be signed in to change notification settings - Fork 722
/
Copy pathclient.go
2274 lines (2044 loc) · 68.8 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
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2015-present Jeevanandam M ([email protected]), All rights reserved.
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
// SPDX-License-Identifier: MIT
package resty
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"errors"
"io"
"maps"
"net/http"
"net/url"
"os"
"reflect"
"slices"
"strings"
"sync"
"time"
)
const (
// MethodGet HTTP method
MethodGet = "GET"
// MethodPost HTTP method
MethodPost = "POST"
// MethodPut HTTP method
MethodPut = "PUT"
// MethodDelete HTTP method
MethodDelete = "DELETE"
// MethodPatch HTTP method
MethodPatch = "PATCH"
// MethodHead HTTP method
MethodHead = "HEAD"
// MethodOptions HTTP method
MethodOptions = "OPTIONS"
// MethodTrace HTTP method
MethodTrace = "TRACE"
)
const (
defaultWatcherPoolingInterval = 24 * time.Hour
)
var (
ErrNotHttpTransportType = errors.New("resty: not a http.Transport type")
ErrUnsupportedRequestBodyKind = errors.New("resty: unsupported request body kind")
hdrUserAgentKey = http.CanonicalHeaderKey("User-Agent")
hdrAcceptKey = http.CanonicalHeaderKey("Accept")
hdrAcceptEncodingKey = http.CanonicalHeaderKey("Accept-Encoding")
hdrContentTypeKey = http.CanonicalHeaderKey("Content-Type")
hdrContentLengthKey = http.CanonicalHeaderKey("Content-Length")
hdrContentEncodingKey = http.CanonicalHeaderKey("Content-Encoding")
hdrContentDisposition = http.CanonicalHeaderKey("Content-Disposition")
hdrAuthorizationKey = http.CanonicalHeaderKey("Authorization")
hdrWwwAuthenticateKey = http.CanonicalHeaderKey("WWW-Authenticate")
hdrRetryAfterKey = http.CanonicalHeaderKey("Retry-After")
hdrCookieKey = http.CanonicalHeaderKey("Cookie")
plainTextType = "text/plain; charset=utf-8"
jsonContentType = "application/json"
formContentType = "application/x-www-form-urlencoded"
jsonKey = "json"
xmlKey = "xml"
defaultAuthScheme = "Bearer"
hdrUserAgentValue = "go-resty/" + Version + " (https://resty.dev)"
bufPool = &sync.Pool{New: func() any { return &bytes.Buffer{} }}
)
type (
// RequestMiddleware type is for request middleware, called before a request is sent
RequestMiddleware func(*Client, *Request) error
// ResponseMiddleware type is for response middleware, called after a response has been received
ResponseMiddleware func(*Client, *Response) error
// DebugLogCallback type is for request and response debug log callback purpose.
// It gets called before Resty logs it
DebugLogCallback func(*DebugLog)
// ErrorHook type is for reacting to request errors, called after all retries were attempted
ErrorHook func(*Request, error)
// SuccessHook type is for reacting to request success
SuccessHook func(*Client, *Response)
// RequestFunc type is for extended manipulation of the Request instance
RequestFunc func(*Request) *Request
// TLSClientConfiger interface is to configure TLS Client configuration on custom transport
// implemented using [http.RoundTripper]
TLSClientConfiger interface {
TLSClientConfig() *tls.Config
SetTLSClientConfig(*tls.Config) error
}
)
// TransportSettings struct is used to define custom dialer and transport
// values for the Resty client. Please refer to individual
// struct fields to know the default values.
//
// Also, refer to https://pkg.go.dev/net/http#Transport for more details.
type TransportSettings struct {
// DialerTimeout, default value is `30` seconds.
DialerTimeout time.Duration
// DialerKeepAlive, default value is `30` seconds.
DialerKeepAlive time.Duration
// IdleConnTimeout, default value is `90` seconds.
IdleConnTimeout time.Duration
// TLSHandshakeTimeout, default value is `10` seconds.
TLSHandshakeTimeout time.Duration
// ExpectContinueTimeout, default value is `1` seconds.
ExpectContinueTimeout time.Duration
// ResponseHeaderTimeout, added to provide ability to
// set value. No default value in Resty, the Go
// HTTP client default value applies.
ResponseHeaderTimeout time.Duration
// MaxIdleConns, default value is `100`.
MaxIdleConns int
// MaxIdleConnsPerHost, default value is `runtime.GOMAXPROCS(0) + 1`.
MaxIdleConnsPerHost int
// DisableKeepAlives, default value is `false`.
DisableKeepAlives bool
// MaxResponseHeaderBytes, added to provide ability to
// set value. No default value in Resty, the Go
// HTTP client default value applies.
MaxResponseHeaderBytes int64
// WriteBufferSize, added to provide ability to
// set value. No default value in Resty, the Go
// HTTP client default value applies.
WriteBufferSize int
// ReadBufferSize, added to provide ability to
// set value. No default value in Resty, the Go
// HTTP client default value applies.
ReadBufferSize int
}
// Client struct is used to create a Resty client with client-level settings,
// these settings apply to all the requests raised from the client.
//
// Resty also provides an option to override most of the client settings
// at [Request] level.
type Client struct {
lock *sync.RWMutex
baseURL string
queryParams url.Values
formData url.Values
pathParams map[string]string
header http.Header
credentials *credentials
authToken string
authScheme string
cookies []*http.Cookie
errorType reflect.Type
debug bool
disableWarn bool
allowMethodGetPayload bool
allowMethodDeletePayload bool
timeout time.Duration
retryCount int
retryWaitTime time.Duration
retryMaxWaitTime time.Duration
retryConditions []RetryConditionFunc
retryHooks []RetryHookFunc
retryStrategy RetryStrategyFunc
isRetryDefaultConditions bool
allowNonIdempotentRetry bool
headerAuthorizationKey string
responseBodyLimit int64
resBodyUnlimitedReads bool
jsonEscapeHTML bool
setContentLength bool
closeConnection bool
notParseResponse bool
isTrace bool
debugBodyLimit int
outputDirectory string
isSaveResponse bool
scheme string
log Logger
ctx context.Context
httpClient *http.Client
proxyURL *url.URL
requestDebugLog DebugLogCallback
responseDebugLog DebugLogCallback
generateCurlCmd bool
debugLogCurlCmd bool
unescapeQueryParams bool
loadBalancer LoadBalancer
beforeRequest []RequestMiddleware
afterResponse []ResponseMiddleware
errorHooks []ErrorHook
invalidHooks []ErrorHook
panicHooks []ErrorHook
successHooks []SuccessHook
contentTypeEncoders map[string]ContentTypeEncoder
contentTypeDecoders map[string]ContentTypeDecoder
contentDecompresserKeys []string
contentDecompressers map[string]ContentDecompresser
certWatcherStopChan chan bool
circuitBreaker *CircuitBreaker
}
// CertWatcherOptions allows configuring a watcher that reloads dynamically TLS certs.
type CertWatcherOptions struct {
// PoolInterval is the frequency at which resty will check if the PEM file needs to be reloaded.
// Default is 24 hours.
PoolInterval time.Duration
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Client methods
//___________________________________
// BaseURL method returns the Base URL value from the client instance.
func (c *Client) BaseURL() string {
c.lock.RLock()
defer c.lock.RUnlock()
return c.baseURL
}
// SetBaseURL method sets the Base URL in the client instance. It will be used with a request
// raised from this client with a relative URL
//
// // Setting HTTP address
// client.SetBaseURL("http://myjeeva.com")
//
// // Setting HTTPS address
// client.SetBaseURL("https://myjeeva.com")
func (c *Client) SetBaseURL(url string) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.baseURL = strings.TrimRight(url, "/")
return c
}
// LoadBalancer method returns the request load balancer instance from the client
// instance. Otherwise returns nil.
func (c *Client) LoadBalancer() LoadBalancer {
c.lock.RLock()
defer c.lock.RUnlock()
return c.loadBalancer
}
// SetLoadBalancer method is used to set the new request load balancer into the client.
func (c *Client) SetLoadBalancer(b LoadBalancer) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.loadBalancer = b
return c
}
// Header method returns the headers from the client instance.
func (c *Client) Header() http.Header {
c.lock.RLock()
defer c.lock.RUnlock()
return c.header
}
// SetHeader method sets a single header and its value in the client instance.
// These headers will be applied to all requests raised from the client instance.
// Also, it can be overridden by request-level header options.
//
// For Example: To set `Content-Type` and `Accept` as `application/json`
//
// client.
// SetHeader("Content-Type", "application/json").
// SetHeader("Accept", "application/json")
//
// See [Request.SetHeader] or [Request.SetHeaders].
func (c *Client) SetHeader(header, value string) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.header.Set(header, value)
return c
}
// SetHeaders method sets multiple headers and their values at one go, and
// these headers will be applied to all requests raised from the client instance.
// Also, it can be overridden at request-level headers options.
//
// For Example: To set `Content-Type` and `Accept` as `application/json`
//
// client.SetHeaders(map[string]string{
// "Content-Type": "application/json",
// "Accept": "application/json",
// })
//
// See [Request.SetHeaders] or [Request.SetHeader].
func (c *Client) SetHeaders(headers map[string]string) *Client {
c.lock.Lock()
defer c.lock.Unlock()
for h, v := range headers {
c.header.Set(h, v)
}
return c
}
// SetHeaderVerbatim method is used to set the HTTP header key and value verbatim in the current request.
// It is typically helpful for legacy applications or servers that require HTTP headers in a certain way
//
// For Example: To set header key as `all_lowercase`, `UPPERCASE`, and `x-cloud-trace-id`
//
// client.
// SetHeaderVerbatim("all_lowercase", "available").
// SetHeaderVerbatim("UPPERCASE", "available").
// SetHeaderVerbatim("x-cloud-trace-id", "798e94019e5fc4d57fbb8901eb4c6cae")
//
// See [Request.SetHeaderVerbatim].
func (c *Client) SetHeaderVerbatim(header, value string) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.header[header] = []string{value}
return c
}
// Context method returns the [context.Context] from the client instance.
func (c *Client) Context() context.Context {
c.lock.RLock()
defer c.lock.RUnlock()
return c.ctx
}
// SetContext method sets the given [context.Context] in the client instance and
// it gets added to [Request] raised from this instance.
func (c *Client) SetContext(ctx context.Context) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.ctx = ctx
return c
}
// CookieJar method returns the HTTP cookie jar instance from the underlying Go HTTP Client.
func (c *Client) CookieJar() http.CookieJar {
return c.Client().Jar
}
// SetCookieJar method sets custom [http.CookieJar] in the resty client. It's a way to override the default.
//
// For Example, sometimes we don't want to save cookies in API mode so that we can remove the default
// CookieJar in resty client.
//
// client.SetCookieJar(nil)
func (c *Client) SetCookieJar(jar http.CookieJar) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.httpClient.Jar = jar
return c
}
// Cookies method returns all cookies registered in the client instance.
func (c *Client) Cookies() []*http.Cookie {
c.lock.RLock()
defer c.lock.RUnlock()
return c.cookies
}
// SetCookie method appends a single cookie to the client instance.
// These cookies will be added to all the requests from this client instance.
//
// client.SetCookie(&http.Cookie{
// Name:"go-resty",
// Value:"This is cookie value",
// })
func (c *Client) SetCookie(hc *http.Cookie) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.cookies = append(c.cookies, hc)
return c
}
// SetCookies method sets an array of cookies in the client instance.
// These cookies will be added to all the requests from this client instance.
//
// cookies := []*http.Cookie{
// &http.Cookie{
// Name:"go-resty-1",
// Value:"This is cookie 1 value",
// },
// &http.Cookie{
// Name:"go-resty-2",
// Value:"This is cookie 2 value",
// },
// }
//
// // Setting a cookies into resty
// client.SetCookies(cookies)
func (c *Client) SetCookies(cs []*http.Cookie) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.cookies = append(c.cookies, cs...)
return c
}
// QueryParams method returns all query parameters and their values from the client instance.
func (c *Client) QueryParams() url.Values {
c.lock.RLock()
defer c.lock.RUnlock()
return c.queryParams
}
// SetQueryParam method sets a single parameter and its value in the client instance.
// It will be formed as a query string for the request.
//
// For Example: `search=kitchen%20papers&size=large`
//
// In the URL after the `?` mark. These query params will be added to all the requests raised from
// this client instance. Also, it can be overridden at the request level.
//
// See [Request.SetQueryParam] or [Request.SetQueryParams].
//
// client.
// SetQueryParam("search", "kitchen papers").
// SetQueryParam("size", "large")
func (c *Client) SetQueryParam(param, value string) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.queryParams.Set(param, value)
return c
}
// SetQueryParams method sets multiple parameters and their values at one go in the client instance.
// It will be formed as a query string for the request.
//
// For Example: `search=kitchen%20papers&size=large`
//
// In the URL after the `?` mark. These query params will be added to all the requests raised from this
// client instance. Also, it can be overridden at the request level.
//
// See [Request.SetQueryParams] or [Request.SetQueryParam].
//
// client.SetQueryParams(map[string]string{
// "search": "kitchen papers",
// "size": "large",
// })
func (c *Client) SetQueryParams(params map[string]string) *Client {
// Do not lock here since there is potential deadlock.
for p, v := range params {
c.SetQueryParam(p, v)
}
return c
}
// FormData method returns the form parameters and their values from the client instance.
func (c *Client) FormData() url.Values {
c.lock.RLock()
defer c.lock.RUnlock()
return c.formData
}
// SetFormData method sets Form parameters and their values in the client instance.
// It applies only to HTTP methods `POST` and `PUT`, and the request content type would be set as
// `application/x-www-form-urlencoded`. These form data will be added to all the requests raised from
// this client instance. Also, it can be overridden at the request level.
//
// See [Request.SetFormData].
//
// client.SetFormData(map[string]string{
// "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F",
// "user_id": "3455454545",
// })
func (c *Client) SetFormData(data map[string]string) *Client {
c.lock.Lock()
defer c.lock.Unlock()
for k, v := range data {
c.formData.Set(k, v)
}
return c
}
// SetBasicAuth method sets the basic authentication header in the HTTP request. For Example:
//
// Authorization: Basic <base64-encoded-value>
//
// For Example: To set the header for username "go-resty" and password "welcome"
//
// client.SetBasicAuth("go-resty", "welcome")
//
// This basic auth information is added to all requests from this client instance.
// It can also be overridden at the request level.
//
// See [Request.SetBasicAuth].
func (c *Client) SetBasicAuth(username, password string) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.credentials = &credentials{Username: username, Password: password}
return c
}
// AuthToken method returns the auth token value registered in the client instance.
func (c *Client) AuthToken() string {
c.lock.RLock()
defer c.lock.RUnlock()
return c.authToken
}
// HeaderAuthorizationKey method returns the HTTP header name for Authorization from the client instance.
func (c *Client) HeaderAuthorizationKey() string {
c.lock.RLock()
defer c.lock.RUnlock()
return c.headerAuthorizationKey
}
// SetAuthToken method sets the auth token of the `Authorization` header for all HTTP requests.
// The default auth scheme is `Bearer`; it can be customized with the method [Client.SetAuthScheme]. For Example:
//
// Authorization: <auth-scheme> <auth-token-value>
//
// For Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F
//
// client.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F")
//
// This auth token gets added to all the requests raised from this client instance.
// Also, it can be overridden at the request level.
//
// See [Request.SetAuthToken].
func (c *Client) SetAuthToken(token string) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.authToken = token
return c
}
// AuthScheme method returns the auth scheme name set in the client instance.
//
// See [Client.SetAuthScheme], [Request.SetAuthScheme].
func (c *Client) AuthScheme() string {
c.lock.RLock()
defer c.lock.RUnlock()
return c.authScheme
}
// SetAuthScheme method sets the auth scheme type in the HTTP request. For Example:
//
// Authorization: <auth-scheme-value> <auth-token-value>
//
// For Example: To set the scheme to use OAuth
//
// client.SetAuthScheme("OAuth")
//
// This auth scheme gets added to all the requests raised from this client instance.
// Also, it can be overridden at the request level.
//
// Information about auth schemes can be found in [RFC 7235], IANA [HTTP Auth schemes].
//
// See [Request.SetAuthScheme].
//
// [RFC 7235]: https://tools.ietf.org/html/rfc7235
// [HTTP Auth schemes]: https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes
func (c *Client) SetAuthScheme(scheme string) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.authScheme = scheme
return c
}
// SetDigestAuth method sets the Digest Auth transport with provided credentials in the client.
// If a server responds with 401 and sends a Digest challenge in the header `WWW-Authenticate`,
// the request will be resent with the appropriate digest `Authorization` header.
//
// For Example: To set the Digest scheme with user "Mufasa" and password "Circle Of Life"
//
// client.SetDigestAuth("Mufasa", "Circle Of Life")
//
// Information about Digest Access Authentication can be found in [RFC 7616].
//
// NOTE:
// - On the QOP `auth-int` scenario, the request body is read into memory to
// compute the body hash that consumes additional memory usage.
// - It is recommended to create a dedicated client instance for digest auth,
// as it does digest auth for all the requests raised by the client.
//
// [RFC 7616]: https://datatracker.ietf.org/doc/html/rfc7616
func (c *Client) SetDigestAuth(username, password string) *Client {
dt := &digestTransport{
credentials: &credentials{username, password},
transport: c.Transport(),
}
c.SetTransport(dt)
return c
}
// R method creates a new request instance; it's used for Get, Post, Put, Delete, Patch, Head, Options, etc.
func (c *Client) R() *Request {
c.lock.RLock()
defer c.lock.RUnlock()
r := &Request{
QueryParams: url.Values{},
FormData: url.Values{},
Header: http.Header{},
Cookies: make([]*http.Cookie, 0),
PathParams: make(map[string]string),
Timeout: c.timeout,
Debug: c.debug,
IsTrace: c.isTrace,
IsSaveResponse: c.isSaveResponse,
AuthScheme: c.authScheme,
AuthToken: c.authToken,
RetryCount: c.retryCount,
RetryWaitTime: c.retryWaitTime,
RetryMaxWaitTime: c.retryMaxWaitTime,
RetryStrategy: c.retryStrategy,
IsRetryDefaultConditions: c.isRetryDefaultConditions,
CloseConnection: c.closeConnection,
DoNotParseResponse: c.notParseResponse,
DebugBodyLimit: c.debugBodyLimit,
ResponseBodyLimit: c.responseBodyLimit,
ResponseBodyUnlimitedReads: c.resBodyUnlimitedReads,
AllowMethodGetPayload: c.allowMethodGetPayload,
AllowMethodDeletePayload: c.allowMethodDeletePayload,
AllowNonIdempotentRetry: c.allowNonIdempotentRetry,
client: c,
baseURL: c.baseURL,
multipartFields: make([]*MultipartField, 0),
jsonEscapeHTML: c.jsonEscapeHTML,
log: c.log,
setContentLength: c.setContentLength,
generateCurlCmd: c.generateCurlCmd,
debugLogCurlCmd: c.debugLogCurlCmd,
unescapeQueryParams: c.unescapeQueryParams,
credentials: c.credentials,
}
if c.ctx != nil {
r.ctx = context.WithoutCancel(c.ctx) // refer to godoc for more info about this function
}
return r
}
// NewRequest method is an alias for method `R()`.
func (c *Client) NewRequest() *Request {
return c.R()
}
// SetRequestMiddlewares method allows Resty users to override the default request
// middlewares sequence
//
// client := New()
// defer client.Close()
//
// client.SetRequestMiddlewares(
// CustomRequest1Middleware,
// CustomRequest2Middleware,
// resty.PrepareRequestMiddleware, // after this, Request.RawRequest is available
// resty.GenerateCurlRequestMiddleware,
// CustomRequest3Middleware,
// CustomRequest4Middleware,
// )
//
// See, [Client.AddRequestMiddleware]
//
// NOTE:
// - It overwrites the existing request middleware list.
// - Be sure to include Resty request middlewares in the request chain at the appropriate spot.
func (c *Client) SetRequestMiddlewares(middlewares ...RequestMiddleware) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.beforeRequest = middlewares
return c
}
// SetResponseMiddlewares method allows Resty users to override the default response
// middlewares sequence
//
// client := New()
// defer client.Close()
//
// client.SetResponseMiddlewares(
// CustomResponse1Middleware,
// CustomResponse2Middleware,
// resty.AutoParseResponseMiddleware, // before this, body is not read except on debug flow
// CustomResponse3Middleware,
// resty.SaveToFileResponseMiddleware, // See, Request.SetOutputFile
// CustomResponse4Middleware,
// CustomResponse5Middleware,
// )
//
// See, [Client.AddResponseMiddleware]
//
// NOTE:
// - It overwrites the existing request middleware list.
// - Be sure to include Resty response middlewares in the response chain at the appropriate spot.
func (c *Client) SetResponseMiddlewares(middlewares ...ResponseMiddleware) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.afterResponse = middlewares
return c
}
func (c *Client) requestMiddlewares() []RequestMiddleware {
c.lock.RLock()
defer c.lock.RUnlock()
return c.beforeRequest
}
// AddRequestMiddleware method appends a request middleware to the before request chain.
// After all requests, middlewares are applied, and the request is sent to the host server.
//
// client.AddRequestMiddleware(func(c *resty.Client, r *resty.Request) error {
// // Now you have access to the Client and Request instance
// // manipulate it as per your need
//
// return nil // if its successful otherwise return error
// })
func (c *Client) AddRequestMiddleware(m RequestMiddleware) *Client {
c.lock.Lock()
defer c.lock.Unlock()
idx := len(c.beforeRequest) - 1
c.beforeRequest = slices.Insert(c.beforeRequest, idx, m)
return c
}
func (c *Client) responseMiddlewares() []ResponseMiddleware {
c.lock.RLock()
defer c.lock.RUnlock()
return c.afterResponse
}
// AddResponseMiddleware method appends response middleware to the after-response chain.
// All the response middlewares are applied; once we receive a response
// from the host server.
//
// client.AddResponseMiddleware(func(c *resty.Client, r *resty.Response) error {
// // Now you have access to the Client and Response instance
// // Also, you could access request via Response.Request i.e., r.Request
// // manipulate it as per your need
//
// return nil // if its successful otherwise return error
// })
func (c *Client) AddResponseMiddleware(m ResponseMiddleware) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.afterResponse = append(c.afterResponse, m)
return c
}
// OnError method adds a callback that will be run whenever a request execution fails.
// This is called after all retries have been attempted (if any).
// If there was a response from the server, the error will be wrapped in [ResponseError]
// which has the last response received from the server.
//
// client.OnError(func(req *resty.Request, err error) {
// if v, ok := err.(*resty.ResponseError); ok {
// // Do something with v.Response
// }
// // Log the error, increment a metric, etc...
// })
//
// Out of the [Client.OnSuccess], [Client.OnError], [Client.OnInvalid], [Client.OnPanic]
// callbacks, exactly one set will be invoked for each call to [Request.Execute] that completes.
//
// NOTE:
// - Do not use [Client] setter methods within OnError hooks; deadlock will happen.
func (c *Client) OnError(h ErrorHook) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.errorHooks = append(c.errorHooks, h)
return c
}
// OnSuccess method adds a callback that will be run whenever a request execution
// succeeds. This is called after all retries have been attempted (if any).
//
// Out of the [Client.OnSuccess], [Client.OnError], [Client.OnInvalid], [Client.OnPanic]
// callbacks, exactly one set will be invoked for each call to [Request.Execute] that completes.
//
// NOTE:
// - Do not use [Client] setter methods within OnSuccess hooks; deadlock will happen.
func (c *Client) OnSuccess(h SuccessHook) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.successHooks = append(c.successHooks, h)
return c
}
// OnInvalid method adds a callback that will be run whenever a request execution
// fails before it starts because the request is invalid.
//
// Out of the [Client.OnSuccess], [Client.OnError], [Client.OnInvalid], [Client.OnPanic]
// callbacks, exactly one set will be invoked for each call to [Request.Execute] that completes.
//
// NOTE:
// - Do not use [Client] setter methods within OnInvalid hooks; deadlock will happen.
func (c *Client) OnInvalid(h ErrorHook) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.invalidHooks = append(c.invalidHooks, h)
return c
}
// OnPanic method adds a callback that will be run whenever a request execution
// panics.
//
// Out of the [Client.OnSuccess], [Client.OnError], [Client.OnInvalid], [Client.OnPanic]
// callbacks, exactly one set will be invoked for each call to [Request.Execute] that completes.
//
// If an [Client.OnSuccess], [Client.OnError], or [Client.OnInvalid] callback panics,
// then exactly one rule can be violated.
//
// NOTE:
// - Do not use [Client] setter methods within OnPanic hooks; deadlock will happen.
func (c *Client) OnPanic(h ErrorHook) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.panicHooks = append(c.panicHooks, h)
return c
}
// ContentTypeEncoders method returns all the registered content type encoders.
func (c *Client) ContentTypeEncoders() map[string]ContentTypeEncoder {
c.lock.RLock()
defer c.lock.RUnlock()
return c.contentTypeEncoders
}
// AddContentTypeEncoder method adds the user-provided Content-Type encoder into a client.
//
// NOTE: It overwrites the encoder function if the given Content-Type key already exists.
func (c *Client) AddContentTypeEncoder(ct string, e ContentTypeEncoder) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.contentTypeEncoders[ct] = e
return c
}
func (c *Client) inferContentTypeEncoder(ct ...string) (ContentTypeEncoder, bool) {
c.lock.RLock()
defer c.lock.RUnlock()
for _, v := range ct {
if d, f := c.contentTypeEncoders[v]; f {
return d, f
}
}
return nil, false
}
// ContentTypeDecoders method returns all the registered content type decoders.
func (c *Client) ContentTypeDecoders() map[string]ContentTypeDecoder {
c.lock.RLock()
defer c.lock.RUnlock()
return c.contentTypeDecoders
}
// AddContentTypeDecoder method adds the user-provided Content-Type decoder into a client.
//
// NOTE: It overwrites the decoder function if the given Content-Type key already exists.
func (c *Client) AddContentTypeDecoder(ct string, d ContentTypeDecoder) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.contentTypeDecoders[ct] = d
return c
}
func (c *Client) inferContentTypeDecoder(ct ...string) (ContentTypeDecoder, bool) {
c.lock.RLock()
defer c.lock.RUnlock()
for _, v := range ct {
if d, f := c.contentTypeDecoders[v]; f {
return d, f
}
}
return nil, false
}
// ContentDecompressers method returns all the registered content-encoding Decompressers.
func (c *Client) ContentDecompressers() map[string]ContentDecompresser {
c.lock.RLock()
defer c.lock.RUnlock()
return c.contentDecompressers
}
// AddContentDecompresser method adds the user-provided Content-Encoding ([RFC 9110]) Decompresser
// and directive into a client.
//
// NOTE: It overwrites the Decompresser function if the given Content-Encoding directive already exists.
//
// [RFC 9110]: https://datatracker.ietf.org/doc/html/rfc9110
func (c *Client) AddContentDecompresser(k string, d ContentDecompresser) *Client {
c.lock.Lock()
defer c.lock.Unlock()
if !slices.Contains(c.contentDecompresserKeys, k) {
c.contentDecompresserKeys = slices.Insert(c.contentDecompresserKeys, 0, k)
}
c.contentDecompressers[k] = d
return c
}
// ContentDecompresserKeys method returns all the registered content-encoding Decompressers
// keys as comma-separated string.
func (c *Client) ContentDecompresserKeys() string {
c.lock.RLock()
defer c.lock.RUnlock()
return strings.Join(c.contentDecompresserKeys, ", ")
}
// SetContentDecompresserKeys method sets given Content-Encoding ([RFC 9110]) directives into the client instance.
//
// It checks the given Content-Encoding exists in the [ContentDecompresser] list before assigning it,
// if it does not exist, it will skip that directive.
//
// Use this method to overwrite the default order. If a new content Decompresser is added,
// that directive will be the first.
//
// [RFC 9110]: https://datatracker.ietf.org/doc/html/rfc9110
func (c *Client) SetContentDecompresserKeys(keys []string) *Client {
result := make([]string, 0)
decoders := c.ContentDecompressers()
for _, k := range keys {
if _, f := decoders[k]; f {
result = append(result, k)
}
}
c.lock.Lock()
defer c.lock.Unlock()
c.contentDecompresserKeys = result
return c
}
// SetCircuitBreaker method sets the Circuit Breaker instance into the client.
// It is used to prevent the client from sending requests that are likely to fail.
// For Example: To use the default Circuit Breaker:
//
// client.SetCircuitBreaker(NewCircuitBreaker())
func (c *Client) SetCircuitBreaker(b *CircuitBreaker) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.circuitBreaker = b
return c
}
// IsDebug method returns `true` if the client is in debug mode; otherwise, it is `false`.
func (c *Client) IsDebug() bool {
c.lock.RLock()
defer c.lock.RUnlock()
return c.debug
}
// EnableDebug method is a helper method for [Client.SetDebug]
func (c *Client) EnableDebug() *Client {
c.SetDebug(true)
return c
}
// DisableDebug method is a helper method for [Client.SetDebug]
func (c *Client) DisableDebug() *Client {
c.SetDebug(false)
return c
}
// SetDebug method enables the debug mode on the Resty client. The client logs details
// of every request and response.
//
// client.SetDebug(true)
// // OR
// client.EnableDebug()
//
// Also, it can be enabled at the request level for a particular request; see [Request.SetDebug].
// - For [Request], it logs information such as HTTP verb, Relative URL path,
// Host, Headers, and Body if it has one.
// - For [Response], it logs information such as Status, Response Time, Headers,
// and Body if it has one.
func (c *Client) SetDebug(d bool) *Client {
c.lock.Lock()
defer c.lock.Unlock()
c.debug = d
return c
}
// DebugBodyLimit method returns the debug body limit value set on the client instance
func (c *Client) DebugBodyLimit() int {
c.lock.RLock()