-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
1762 lines (1566 loc) · 53.2 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
package req
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/xml"
"errors"
"io"
"net"
"net/http"
"net/http/cookiejar"
urlpkg "net/url"
"os"
"reflect"
"strings"
"time"
utls "github.com/refraction-networking/utls"
"golang.org/x/net/publicsuffix"
"github.com/imroc/req/v3/http2"
"github.com/imroc/req/v3/internal/header"
"github.com/imroc/req/v3/internal/util"
)
// DefaultClient returns the global default Client.
func DefaultClient() *Client {
return defaultClient
}
// SetDefaultClient override the global default Client.
func SetDefaultClient(c *Client) {
if c != nil {
defaultClient = c
}
}
var defaultClient = C()
// Client is the req's http client.
type Client struct {
BaseURL string
PathParams map[string]string
QueryParams urlpkg.Values
FormData urlpkg.Values
DebugLog bool
AllowGetMethodPayload bool
*Transport
cookiejarFactory func() *cookiejar.Jar
trace bool
disableAutoReadResponse bool
commonErrorType reflect.Type
retryOption *retryOption
jsonMarshal func(v interface{}) ([]byte, error)
jsonUnmarshal func(data []byte, v interface{}) error
xmlMarshal func(v interface{}) ([]byte, error)
xmlUnmarshal func(data []byte, v interface{}) error
multipartBoundaryFunc func() string
outputDirectory string
scheme string
log Logger
dumpOptions *DumpOptions
httpClient *http.Client
beforeRequest []RequestMiddleware
udBeforeRequest []RequestMiddleware
afterResponse []ResponseMiddleware
wrappedRoundTrip RoundTripper
roundTripWrappers []RoundTripWrapper
responseBodyTransformer func(rawBody []byte, req *Request, resp *Response) (transformedBody []byte, err error)
resultStateCheckFunc func(resp *Response) ResultState
onError ErrorHook
}
type ErrorHook func(client *Client, req *Request, resp *Response, err error)
// R create a new request.
func (c *Client) R() *Request {
return &Request{
client: c,
retryOption: c.retryOption.Clone(),
}
}
// Get create a new GET request, accepts 0 or 1 url.
func (c *Client) Get(url ...string) *Request {
r := c.R()
if len(url) > 0 {
r.RawURL = url[0]
}
r.Method = http.MethodGet
return r
}
// Post create a new POST request.
func (c *Client) Post(url ...string) *Request {
r := c.R()
if len(url) > 0 {
r.RawURL = url[0]
}
r.Method = http.MethodPost
return r
}
// Patch create a new PATCH request.
func (c *Client) Patch(url ...string) *Request {
r := c.R()
if len(url) > 0 {
r.RawURL = url[0]
}
r.Method = http.MethodPatch
return r
}
// Delete create a new DELETE request.
func (c *Client) Delete(url ...string) *Request {
r := c.R()
if len(url) > 0 {
r.RawURL = url[0]
}
r.Method = http.MethodDelete
return r
}
// Put create a new PUT request.
func (c *Client) Put(url ...string) *Request {
r := c.R()
if len(url) > 0 {
r.RawURL = url[0]
}
r.Method = http.MethodPut
return r
}
// Head create a new HEAD request.
func (c *Client) Head(url ...string) *Request {
r := c.R()
if len(url) > 0 {
r.RawURL = url[0]
}
r.Method = http.MethodHead
return r
}
// Options create a new OPTIONS request.
func (c *Client) Options(url ...string) *Request {
r := c.R()
if len(url) > 0 {
r.RawURL = url[0]
}
r.Method = http.MethodOptions
return r
}
// GetTransport return the underlying transport.
func (c *Client) GetTransport() *Transport {
return c.Transport
}
// SetResponseBodyTransformer set the response body transformer, which can modify the
// response body before unmarshalled if auto-read response body is not disabled.
func (c *Client) SetResponseBodyTransformer(fn func(rawBody []byte, req *Request, resp *Response) (transformedBody []byte, err error)) *Client {
c.responseBodyTransformer = fn
return c
}
// SetCommonError set the common result that response body will be unmarshalled to
// if no error occurs but Response.ResultState returns ErrorState, by default it
// is HTTP status `code >= 400`, you can also use SetCommonResultStateChecker
// to customize the result state check logic.
//
// Deprecated: Use SetCommonErrorResult instead.
func (c *Client) SetCommonError(err interface{}) *Client {
return c.SetCommonErrorResult(err)
}
// SetCommonErrorResult set the common result that response body will be unmarshalled to
// if no error occurs but Response.ResultState returns ErrorState, by default it
// is HTTP status `code >= 400`, you can also use SetCommonResultStateChecker
// to customize the result state check logic.
func (c *Client) SetCommonErrorResult(err interface{}) *Client {
if err != nil {
c.commonErrorType = util.GetType(err)
}
return c
}
// ResultState represents the state of the result.
type ResultState int
const (
// SuccessState indicates the response is in success state,
// and result will be unmarshalled if Request.SetSuccessResult
// is called.
SuccessState ResultState = iota
// ErrorState indicates the response is in error state,
// and result will be unmarshalled if Request.SetErrorResult
// or Client.SetCommonErrorResult is called.
ErrorState
// UnknownState indicates the response is in unknown state,
// and handler will be invoked if Request.SetUnknownResultHandlerFunc
// or Client.SetCommonUnknownResultHandlerFunc is called.
UnknownState
)
// SetResultStateCheckFunc overrides the default result state checker with customized one,
// which returns SuccessState when HTTP status `code >= 200 and <= 299`, and returns
// ErrorState when HTTP status `code >= 400`, otherwise returns UnknownState.
func (c *Client) SetResultStateCheckFunc(fn func(resp *Response) ResultState) *Client {
c.resultStateCheckFunc = fn
return c
}
// SetCommonFormDataFromValues set the form data from url.Values for requests
// fired from the client which request method allows payload.
func (c *Client) SetCommonFormDataFromValues(data urlpkg.Values) *Client {
if c.FormData == nil {
c.FormData = urlpkg.Values{}
}
for k, v := range data {
for _, kv := range v {
c.FormData.Add(k, kv)
}
}
return c
}
// SetCommonFormData set the form data from map for requests fired from the client
// which request method allows payload.
func (c *Client) SetCommonFormData(data map[string]string) *Client {
if c.FormData == nil {
c.FormData = urlpkg.Values{}
}
for k, v := range data {
c.FormData.Set(k, v)
}
return c
}
// SetMultipartBoundaryFunc overrides the default function used to generate
// boundary delimiters for "multipart/form-data" requests with a customized one,
// which returns a boundary delimiter (without the two leading hyphens).
//
// Boundary delimiter may only contain certain ASCII characters, and must be
// non-empty and at most 70 bytes long (see RFC 2046, Section 5.1.1).
func (c *Client) SetMultipartBoundaryFunc(fn func() string) *Client {
c.multipartBoundaryFunc = fn
return c
}
// SetBaseURL set the default base URL, will be used if request URL is
// a relative URL.
func (c *Client) SetBaseURL(u string) *Client {
c.BaseURL = strings.TrimRight(u, "/")
return c
}
// SetOutputDirectory set output directory that response will
// be downloaded to.
func (c *Client) SetOutputDirectory(dir string) *Client {
c.outputDirectory = dir
return c
}
// SetCertFromFile helps to set client certificates from cert and key file.
func (c *Client) SetCertFromFile(certFile, keyFile string) *Client {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
c.log.Errorf("failed to load client cert: %v", err)
return c
}
config := c.GetTLSClientConfig()
config.Certificates = append(config.Certificates, cert)
return c
}
// SetCerts set client certificates.
func (c *Client) SetCerts(certs ...tls.Certificate) *Client {
config := c.GetTLSClientConfig()
config.Certificates = append(config.Certificates, certs...)
return c
}
func (c *Client) appendRootCertData(data []byte) {
config := c.GetTLSClientConfig()
if config.RootCAs == nil {
config.RootCAs = x509.NewCertPool()
}
config.RootCAs.AppendCertsFromPEM(data)
}
// SetRootCertFromString set root certificates from string.
func (c *Client) SetRootCertFromString(pemContent string) *Client {
c.appendRootCertData([]byte(pemContent))
return c
}
// SetRootCertsFromFile set root certificates from files.
func (c *Client) SetRootCertsFromFile(pemFiles ...string) *Client {
for _, pemFile := range pemFiles {
rootPemData, err := os.ReadFile(pemFile)
if err != nil {
c.log.Errorf("failed to read root cert file: %v", err)
return c
}
c.appendRootCertData(rootPemData)
}
return c
}
// GetTLSClientConfig return the underlying tls.Config.
func (c *Client) GetTLSClientConfig() *tls.Config {
if c.TLSClientConfig == nil {
c.TLSClientConfig = &tls.Config{
NextProtos: []string{"h2", "http/1.1"},
}
}
return c.TLSClientConfig
}
func (c *Client) defaultCheckRedirect(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return errors.New("stopped after 10 redirects")
}
if c.DebugLog {
c.log.Debugf("<redirect> %s %s", req.Method, req.URL.String())
}
return nil
}
// SetRedirectPolicy set the RedirectPolicy which controls the behavior of receiving redirect
// responses (usually responses with 301 and 302 status code), see the predefined
// AllowedDomainRedirectPolicy, AllowedHostRedirectPolicy, MaxRedirectPolicy, NoRedirectPolicy,
// SameDomainRedirectPolicy and SameHostRedirectPolicy.
func (c *Client) SetRedirectPolicy(policies ...RedirectPolicy) *Client {
if len(policies) == 0 {
return c
}
c.httpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
for _, f := range policies {
if f == nil {
continue
}
err := f(req, via)
if err != nil {
return err
}
}
if c.DebugLog {
c.log.Debugf("<redirect> %s %s", req.Method, req.URL.String())
}
return nil
}
return c
}
// DisableKeepAlives disable the HTTP keep-alives (enabled by default)
// and will only use the connection to the server for a single
// HTTP request.
//
// This is unrelated to the similarly named TCP keep-alives.
func (c *Client) DisableKeepAlives() *Client {
c.Transport.DisableKeepAlives = true
return c
}
// EnableKeepAlives enables HTTP keep-alives (enabled by default).
func (c *Client) EnableKeepAlives() *Client {
c.Transport.DisableKeepAlives = false
return c
}
// DisableCompression disables the compression (enabled by default),
// which prevents the Transport from requesting compression
// with an "Accept-Encoding: gzip" request header when the
// Request contains no existing Accept-Encoding value. If
// the Transport requests gzip on its own and gets a gzipped
// response, it's transparently decoded in the Response.Body.
// However, if the user explicitly requested gzip it is not
// automatically uncompressed.
func (c *Client) DisableCompression() *Client {
c.Transport.DisableCompression = true
return c
}
// EnableCompression enables the compression (enabled by default).
func (c *Client) EnableCompression() *Client {
c.Transport.DisableCompression = false
return c
}
// EnableAutoDecompress enables the automatic decompression (disabled by default).
func (c *Client) EnableAutoDecompress() *Client {
c.Transport.AutoDecompression = true
return c
}
// DisableAutoDecompress disables the automatic decompression (disabled by default).
func (c *Client) DisableAutoDecompress() *Client {
c.Transport.AutoDecompression = false
return c
}
// SetTLSClientConfig set the TLS client config. Be careful! Usually
// you don't need this, you can directly set the tls configuration with
// methods like EnableInsecureSkipVerify, SetCerts etc. Or you can call
// GetTLSClientConfig to get the current tls configuration to avoid
// overwriting some important configurations, such as not setting NextProtos
// will not use http2 by default.
func (c *Client) SetTLSClientConfig(conf *tls.Config) *Client {
c.TLSClientConfig = conf
return c
}
// EnableInsecureSkipVerify enable send https without verifing
// the server's certificates (disabled by default).
func (c *Client) EnableInsecureSkipVerify() *Client {
c.GetTLSClientConfig().InsecureSkipVerify = true
return c
}
// DisableInsecureSkipVerify disable send https without verifing
// the server's certificates (disabled by default).
func (c *Client) DisableInsecureSkipVerify() *Client {
c.GetTLSClientConfig().InsecureSkipVerify = false
return c
}
// SetCommonQueryParams set URL query parameters with a map
// for requests fired from the client.
func (c *Client) SetCommonQueryParams(params map[string]string) *Client {
for k, v := range params {
c.SetCommonQueryParam(k, v)
}
return c
}
// AddCommonQueryParam add a URL query parameter with a key-value
// pair for requests fired from the client.
func (c *Client) AddCommonQueryParam(key, value string) *Client {
if c.QueryParams == nil {
c.QueryParams = make(urlpkg.Values)
}
c.QueryParams.Add(key, value)
return c
}
// AddCommonQueryParams add one or more values of specified URL query parameter
// for requests fired from the client.
func (c *Client) AddCommonQueryParams(key string, values ...string) *Client {
if c.QueryParams == nil {
c.QueryParams = make(urlpkg.Values)
}
vs := c.QueryParams[key]
vs = append(vs, values...)
c.QueryParams[key] = vs
return c
}
func (c *Client) pathParams() map[string]string {
if c.PathParams == nil {
c.PathParams = make(map[string]string)
}
return c.PathParams
}
// SetCommonPathParam set a path parameter for requests fired from the client.
func (c *Client) SetCommonPathParam(key, value string) *Client {
c.pathParams()[key] = value
return c
}
// SetCommonPathParams set path parameters for requests fired from the client.
func (c *Client) SetCommonPathParams(pathParams map[string]string) *Client {
m := c.pathParams()
for k, v := range pathParams {
m[k] = v
}
return c
}
// SetCommonQueryParam set a URL query parameter with a key-value
// pair for requests fired from the client.
func (c *Client) SetCommonQueryParam(key, value string) *Client {
if c.QueryParams == nil {
c.QueryParams = make(urlpkg.Values)
}
c.QueryParams.Set(key, value)
return c
}
// SetCommonQueryString set URL query parameters with a raw query string
// for requests fired from the client.
func (c *Client) SetCommonQueryString(query string) *Client {
params, err := urlpkg.ParseQuery(strings.TrimSpace(query))
if err != nil {
c.log.Warnf("failed to parse query string (%s): %v", query, err)
return c
}
if c.QueryParams == nil {
c.QueryParams = make(urlpkg.Values)
}
for p, v := range params {
for _, pv := range v {
c.QueryParams.Add(p, pv)
}
}
return c
}
// SetCommonCookies set HTTP cookies for requests fired from the client.
func (c *Client) SetCommonCookies(cookies ...*http.Cookie) *Client {
c.Cookies = append(c.Cookies, cookies...)
return c
}
// DisableDebugLog disable debug level log (disabled by default).
func (c *Client) DisableDebugLog() *Client {
c.DebugLog = false
return c
}
// EnableDebugLog enable debug level log (disabled by default).
func (c *Client) EnableDebugLog() *Client {
c.DebugLog = true
return c
}
// DevMode enables:
// 1. Dump content of all requests and responses to see details.
// 2. Output debug level log for deeper insights.
// 3. Trace all requests, so you can get trace info to analyze performance.
func (c *Client) DevMode() *Client {
return c.EnableDumpAll().
EnableDebugLog().
EnableTraceAll()
}
// SetScheme set the default scheme for client, will be used when
// there is no scheme in the request URL (e.g. "github.com/imroc/req").
func (c *Client) SetScheme(scheme string) *Client {
if !util.IsStringEmpty(scheme) {
c.scheme = strings.TrimSpace(scheme)
}
return c
}
// GetLogger return the internal logger, usually used in middleware.
func (c *Client) GetLogger() Logger {
if c.log != nil {
return c.log
}
c.log = createDefaultLogger()
return c.log
}
// SetLogger set the customized logger for client, will disable log if set to nil.
func (c *Client) SetLogger(log Logger) *Client {
if log == nil {
c.log = &disableLogger{}
return c
}
c.log = log
return c
}
// SetTimeout set timeout for requests fired from the client.
func (c *Client) SetTimeout(d time.Duration) *Client {
c.httpClient.Timeout = d
return c
}
func (c *Client) getDumpOptions() *DumpOptions {
if c.dumpOptions == nil {
c.dumpOptions = newDefaultDumpOptions()
}
return c.dumpOptions
}
// EnableDumpAll enable dump for requests fired from the client, including
// all content for the request and response by default.
func (c *Client) EnableDumpAll() *Client {
if c.Dump != nil { // dump already started
return c
}
c.EnableDump(c.getDumpOptions())
return c
}
// EnableDumpAllToFile enable dump for requests fired from the
// client and output to the specified file.
func (c *Client) EnableDumpAllToFile(filename string) *Client {
file, err := os.Create(filename)
if err != nil {
c.log.Errorf("create dump file error: %v", err)
return c
}
c.getDumpOptions().Output = file
c.EnableDumpAll()
return c
}
// EnableDumpAllTo enable dump for requests fired from the
// client and output to the specified io.Writer.
func (c *Client) EnableDumpAllTo(output io.Writer) *Client {
c.getDumpOptions().Output = output
c.EnableDumpAll()
return c
}
// EnableDumpAllAsync enable dump for requests fired from the
// client and output asynchronously, can be used for debugging
// in production environment without affecting performance.
func (c *Client) EnableDumpAllAsync() *Client {
o := c.getDumpOptions()
o.Async = true
c.EnableDumpAll()
return c
}
// EnableDumpAllWithoutRequestBody enable dump for requests fired
// from the client without request body, can be used in the upload
// request to avoid dumping the unreadable binary content.
func (c *Client) EnableDumpAllWithoutRequestBody() *Client {
o := c.getDumpOptions()
o.RequestBody = false
c.EnableDumpAll()
return c
}
// EnableDumpAllWithoutResponseBody enable dump for requests fired
// from the client without response body, can be used in the download
// request to avoid dumping the unreadable binary content.
func (c *Client) EnableDumpAllWithoutResponseBody() *Client {
o := c.getDumpOptions()
o.ResponseBody = false
c.EnableDumpAll()
return c
}
// EnableDumpAllWithoutResponse enable dump for requests fired from
// the client without response, can be used if you only care about
// the request.
func (c *Client) EnableDumpAllWithoutResponse() *Client {
o := c.getDumpOptions()
o.ResponseBody = false
o.ResponseHeader = false
c.EnableDumpAll()
return c
}
// EnableDumpAllWithoutRequest enables dump for requests fired from
// the client without request, can be used if you only care about
// the response.
func (c *Client) EnableDumpAllWithoutRequest() *Client {
o := c.getDumpOptions()
o.RequestHeader = false
o.RequestBody = false
c.EnableDumpAll()
return c
}
// EnableDumpAllWithoutHeader enable dump for requests fired from
// the client without header, can be used if you only care about
// the body.
func (c *Client) EnableDumpAllWithoutHeader() *Client {
o := c.getDumpOptions()
o.RequestHeader = false
o.ResponseHeader = false
c.EnableDumpAll()
return c
}
// EnableDumpAllWithoutBody enable dump for requests fired from
// the client without body, can be used if you only care about
// the header.
func (c *Client) EnableDumpAllWithoutBody() *Client {
o := c.getDumpOptions()
o.RequestBody = false
o.ResponseBody = false
c.EnableDumpAll()
return c
}
// EnableDumpEachRequest enable dump at the request-level for each request, and only
// temporarily stores the dump content in memory, call Response.Dump() to get the
// dump content when needed.
func (c *Client) EnableDumpEachRequest() *Client {
return c.OnBeforeRequest(func(client *Client, req *Request) error {
if req.RetryAttempt == 0 { // Ignore on retry, no need to repeat enable dump.
req.EnableDump()
}
return nil
})
}
// EnableDumpEachRequestWithoutBody enable dump without body at the request-level for
// each request, and only temporarily stores the dump content in memory, call
// Response.Dump() to get the dump content when needed.
func (c *Client) EnableDumpEachRequestWithoutBody() *Client {
return c.OnBeforeRequest(func(client *Client, req *Request) error {
if req.RetryAttempt == 0 { // Ignore on retry, no need to repeat enable dump.
req.EnableDumpWithoutBody()
}
return nil
})
}
// EnableDumpEachRequestWithoutHeader enable dump without header at the request-level for
// each request, and only temporarily stores the dump content in memory, call
// Response.Dump() to get the dump content when needed.
func (c *Client) EnableDumpEachRequestWithoutHeader() *Client {
return c.OnBeforeRequest(func(client *Client, req *Request) error {
if req.RetryAttempt == 0 { // Ignore on retry, no need to repeat enable dump.
req.EnableDumpWithoutHeader()
}
return nil
})
}
// EnableDumpEachRequestWithoutRequest enable dump without request at the request-level for
// each request, and only temporarily stores the dump content in memory, call
// Response.Dump() to get the dump content when needed.
func (c *Client) EnableDumpEachRequestWithoutRequest() *Client {
return c.OnBeforeRequest(func(client *Client, req *Request) error {
if req.RetryAttempt == 0 { // Ignore on retry, no need to repeat enable dump.
req.EnableDumpWithoutRequest()
}
return nil
})
}
// EnableDumpEachRequestWithoutResponse enable dump without response at the request-level for
// each request, and only temporarily stores the dump content in memory, call
// Response.Dump() to get the dump content when needed.
func (c *Client) EnableDumpEachRequestWithoutResponse() *Client {
return c.OnBeforeRequest(func(client *Client, req *Request) error {
if req.RetryAttempt == 0 { // Ignore on retry, no need to repeat enable dump.
req.EnableDumpWithoutResponse()
}
return nil
})
}
// EnableDumpEachRequestWithoutResponseBody enable dump without response body at the
// request-level for each request, and only temporarily stores the dump content in memory,
// call Response.Dump() to get the dump content when needed.
func (c *Client) EnableDumpEachRequestWithoutResponseBody() *Client {
return c.OnBeforeRequest(func(client *Client, req *Request) error {
if req.RetryAttempt == 0 { // Ignore on retry, no need to repeat enable dump.
req.EnableDumpWithoutResponseBody()
}
return nil
})
}
// EnableDumpEachRequestWithoutRequestBody enable dump without request body at the
// request-level for each request, and only temporarily stores the dump content in memory,
// call Response.Dump() to get the dump content when needed.
func (c *Client) EnableDumpEachRequestWithoutRequestBody() *Client {
return c.OnBeforeRequest(func(client *Client, req *Request) error {
if req.RetryAttempt == 0 { // Ignore on retry, no need to repeat enable dump.
req.EnableDumpWithoutRequestBody()
}
return nil
})
}
// NewRequest is the alias of R()
func (c *Client) NewRequest() *Request {
return c.R()
}
func (c *Client) NewParallelDownload(url string) *ParallelDownload {
return &ParallelDownload{
url: url,
client: c,
}
}
// DisableAutoReadResponse disable read response body automatically (enabled by default).
func (c *Client) DisableAutoReadResponse() *Client {
c.disableAutoReadResponse = true
return c
}
// EnableAutoReadResponse enable read response body automatically (enabled by default).
func (c *Client) EnableAutoReadResponse() *Client {
c.disableAutoReadResponse = false
return c
}
// SetAutoDecodeContentType set the content types that will be auto-detected and decode to utf-8
// (e.g. "json", "xml", "html", "text").
func (c *Client) SetAutoDecodeContentType(contentTypes ...string) *Client {
c.Transport.SetAutoDecodeContentType(contentTypes...)
return c
}
// SetAutoDecodeContentTypeFunc set the function that determines whether the specified `Content-Type` should be auto-detected and decode to utf-8.
func (c *Client) SetAutoDecodeContentTypeFunc(fn func(contentType string) bool) *Client {
c.Transport.SetAutoDecodeContentTypeFunc(fn)
return c
}
// SetAutoDecodeAllContentType enable try auto-detect charset and decode all content type to utf-8.
func (c *Client) SetAutoDecodeAllContentType() *Client {
c.Transport.SetAutoDecodeAllContentType()
return c
}
// DisableAutoDecode disable auto-detect charset and decode to utf-8 (enabled by default).
func (c *Client) DisableAutoDecode() *Client {
c.Transport.DisableAutoDecode()
return c
}
// EnableAutoDecode enable auto-detect charset and decode to utf-8 (enabled by default).
func (c *Client) EnableAutoDecode() *Client {
c.Transport.EnableAutoDecode()
return c
}
// SetUserAgent set the "User-Agent" header for requests fired from the client.
func (c *Client) SetUserAgent(userAgent string) *Client {
return c.SetCommonHeader(header.UserAgent, userAgent)
}
// SetCommonBearerAuthToken set the bearer auth token for requests fired from the client.
func (c *Client) SetCommonBearerAuthToken(token string) *Client {
return c.SetCommonHeader(header.Authorization, "Bearer "+token)
}
// SetCommonBasicAuth set the basic auth for requests fired from
// the client.
func (c *Client) SetCommonBasicAuth(username, password string) *Client {
c.SetCommonHeader(header.Authorization, util.BasicAuthHeaderValue(username, password))
return c
}
// SetCommonDigestAuth sets the Digest Access auth scheme for requests fired from the client. If a server responds with
// 401 and sends a Digest challenge in the WWW-Authenticate Header, requests will be resent with the appropriate
// Authorization Header.
//
// For Example: To set the Digest scheme with user "roc" and password "123456"
//
// client.SetCommonDigestAuth("roc", "123456")
//
// Information about Digest Access Authentication can be found in RFC7616:
//
// https://datatracker.ietf.org/doc/html/rfc7616
//
// See `Request.SetDigestAuth`
func (c *Client) SetCommonDigestAuth(username, password string) *Client {
c.OnAfterResponse(handleDigestAuthFunc(username, password))
return c
}
// SetCommonHeaders set headers for requests fired from the client.
func (c *Client) SetCommonHeaders(hdrs map[string]string) *Client {
for k, v := range hdrs {
c.SetCommonHeader(k, v)
}
return c
}
// SetCommonHeader set a header for requests fired from the client.
func (c *Client) SetCommonHeader(key, value string) *Client {
if c.Headers == nil {
c.Headers = make(http.Header)
}
c.Headers.Set(key, value)
return c
}
// SetCommonHeaderNonCanonical set a header for requests fired from
// the client which key is a non-canonical key (keep case unchanged),
// only valid for HTTP/1.1.
func (c *Client) SetCommonHeaderNonCanonical(key, value string) *Client {
if c.Headers == nil {
c.Headers = make(http.Header)
}
c.Headers[key] = append(c.Headers[key], value)
return c
}
// SetCommonHeadersNonCanonical set headers for requests fired from the
// client which key is a non-canonical key (keep case unchanged), only
// valid for HTTP/1.1.
func (c *Client) SetCommonHeadersNonCanonical(hdrs map[string]string) *Client {
for k, v := range hdrs {
c.SetCommonHeaderNonCanonical(k, v)
}
return c
}
// SetCommonHeaderOrder set the order of the http header requests fired from the
// client (case-insensitive).
// For example:
//
// client.R().SetCommonHeaderOrder(
// "custom-header",
// "cookie",
// "user-agent",
// "accept-encoding",
// ).Get(url
func (c *Client) SetCommonHeaderOrder(keys ...string) *Client {
c.Transport.WrapRoundTripFunc(func(rt http.RoundTripper) HttpRoundTripFunc {
return func(req *http.Request) (resp *http.Response, err error) {
if req.Header == nil {
req.Header = make(http.Header)
}
req.Header[HeaderOderKey] = keys
return rt.RoundTrip(req)
}
})
return c
}
// SetCommonPseudoHeaderOder set the order of the pseudo http header requests fired
// from the client (case-insensitive).
// Note this is only valid for http2 and http3.
// For example:
//
// client.SetCommonPseudoHeaderOder(
// ":scheme",
// ":authority",
// ":path",
// ":method",
// )
func (c *Client) SetCommonPseudoHeaderOder(keys ...string) *Client {
c.Transport.WrapRoundTripFunc(func(rt http.RoundTripper) HttpRoundTripFunc {
return func(req *http.Request) (resp *http.Response, err error) {
if req.Header == nil {
req.Header = make(http.Header)
}
req.Header[PseudoHeaderOderKey] = keys
return rt.RoundTrip(req)
}
})
return c
}
// SetHTTP2SettingsFrame set the ordered http2 settings frame.
func (c *Client) SetHTTP2SettingsFrame(settings ...http2.Setting) *Client {
c.Transport.SetHTTP2SettingsFrame(settings...)
return c
}
// SetHTTP2ConnectionFlow set the default http2 connection flow, which is the increment
// value of initial WINDOW_UPDATE frame.
func (c *Client) SetHTTP2ConnectionFlow(flow uint32) *Client {
c.Transport.SetHTTP2ConnectionFlow(flow)
return c
}
// SetHTTP2HeaderPriority set the header priority param.
func (c *Client) SetHTTP2HeaderPriority(priority http2.PriorityParam) *Client {
c.Transport.SetHTTP2HeaderPriority(priority)
return c
}
// SetHTTP2PriorityFrames set the ordered http2 priority frames.
func (c *Client) SetHTTP2PriorityFrames(frames ...http2.PriorityFrame) *Client {
c.Transport.SetHTTP2PriorityFrames(frames...)
return c
}
// SetCommonContentType set the `Content-Type` header for requests fired
// from the client.
func (c *Client) SetCommonContentType(ct string) *Client {
c.SetCommonHeader(header.ContentType, ct)
return c
}
// DisableDumpAll disable dump for requests fired from the client.
func (c *Client) DisableDumpAll() *Client {
c.DisableDump()
return c
}
// SetCommonDumpOptions configures the underlying Transport's DumpOptions
// for requests fired from the client.
func (c *Client) SetCommonDumpOptions(opt *DumpOptions) *Client {
if opt == nil {
return c
}
if opt.Output == nil {
if c.dumpOptions != nil {
opt.Output = c.dumpOptions.Output
} else {
opt.Output = os.Stdout
}
}
c.dumpOptions = opt
if c.Dump != nil {
c.Dump.SetOptions(dumpOptions{opt})