forked from imroc/req
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
1205 lines (1072 loc) · 34 KB
/
request.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"
"errors"
"fmt"
"io"
"net/http"
urlpkg "net/url"
"os"
"path/filepath"
"reflect"
"strings"
"time"
"github.com/hashicorp/go-multierror"
"github.com/imroc/req/v3/internal/dump"
"github.com/imroc/req/v3/internal/header"
"github.com/imroc/req/v3/internal/util"
)
// Request struct is used to compose and fire individual request from
// req client. Request provides lots of chainable settings which can
// override client level settings.
type Request struct {
PathParams map[string]string
QueryParams urlpkg.Values
FormData urlpkg.Values
Headers http.Header
Cookies []*http.Cookie
Result interface{}
Error interface{}
RawRequest *http.Request
StartTime time.Time
RetryAttempt int
RawURL string // read only
Method string
Body []byte
GetBody GetContentFunc
// URL is an auto-generated field, and is nil in request middleware (OnBeforeRequest),
// consider using RawURL if you want, it's not nil in client middleware (WrapRoundTripFunc)
URL *urlpkg.URL
isMultiPart bool
disableAutoReadResponse bool
forceChunkedEncoding bool
isSaveResponse bool
close bool
error error
client *Client
uploadCallback UploadCallback
uploadCallbackInterval time.Duration
downloadCallback DownloadCallback
downloadCallbackInterval time.Duration
unReplayableBody io.ReadCloser
retryOption *retryOption
bodyReadCloser io.ReadCloser
dumpOptions *DumpOptions
marshalBody interface{}
ctx context.Context
uploadFiles []*FileUpload
uploadReader []io.ReadCloser
outputFile string
output io.Writer
trace *clientTrace
dumpBuffer *bytes.Buffer
responseReturnTime time.Time
afterResponse []ResponseMiddleware
}
type GetContentFunc func() (io.ReadCloser, error)
func (r *Request) getHeader(key string) string {
if r.Headers == nil {
return ""
}
return r.Headers.Get(key)
}
// TraceInfo returns the trace information, only available if trace is enabled
// (see Request.EnableTrace and Client.EnableTraceAll).
func (r *Request) TraceInfo() TraceInfo {
ct := r.trace
if ct == nil {
return TraceInfo{}
}
ti := TraceInfo{
IsConnReused: ct.gotConnInfo.Reused,
IsConnWasIdle: ct.gotConnInfo.WasIdle,
ConnIdleTime: ct.gotConnInfo.IdleTime,
}
endTime := ct.endTime
if endTime.IsZero() { // in case timeout
endTime = r.responseReturnTime
}
if !ct.tlsHandshakeStart.IsZero() {
if !ct.tlsHandshakeDone.IsZero() {
ti.TLSHandshakeTime = ct.tlsHandshakeDone.Sub(ct.tlsHandshakeStart)
} else {
ti.TLSHandshakeTime = endTime.Sub(ct.tlsHandshakeStart)
}
}
if ct.gotConnInfo.Reused {
ti.TotalTime = endTime.Sub(ct.getConn)
} else {
if ct.dnsStart.IsZero() {
ti.TotalTime = endTime.Sub(r.StartTime)
} else {
ti.TotalTime = endTime.Sub(ct.dnsStart)
}
}
dnsDone := ct.dnsDone
if dnsDone.IsZero() {
dnsDone = endTime
}
if !ct.dnsStart.IsZero() {
ti.DNSLookupTime = dnsDone.Sub(ct.dnsStart)
}
// Only calculate on successful connections
if !ct.connectDone.IsZero() {
ti.TCPConnectTime = ct.connectDone.Sub(dnsDone)
}
// Only calculate on successful connections
if !ct.gotConn.IsZero() {
ti.ConnectTime = ct.gotConn.Sub(ct.getConn)
}
// Only calculate on successful connections
if !ct.gotFirstResponseByte.IsZero() {
ti.FirstResponseTime = ct.gotFirstResponseByte.Sub(ct.gotConn)
ti.ResponseTime = endTime.Sub(ct.gotFirstResponseByte)
}
// Capture remote address info when connection is non-nil
if ct.gotConnInfo.Conn != nil {
ti.RemoteAddr = ct.gotConnInfo.Conn.RemoteAddr()
}
return ti
}
// HeaderToString get all header as string.
func (r *Request) HeaderToString() string {
return convertHeaderToString(r.Headers)
}
// SetURL set the url for request.
func (r *Request) SetURL(url string) *Request {
r.RawURL = url
return r
}
// SetFormDataFromValues set the form data from url.Values, will not
// been used if request method does not allow payload.
func (r *Request) SetFormDataFromValues(data urlpkg.Values) *Request {
if r.FormData == nil {
r.FormData = urlpkg.Values{}
}
for k, v := range data {
for _, kv := range v {
r.FormData.Add(k, kv)
}
}
return r
}
// SetFormData set the form data from a map, will not been used
// if request method does not allow payload.
func (r *Request) SetFormData(data map[string]string) *Request {
if r.FormData == nil {
r.FormData = urlpkg.Values{}
}
for k, v := range data {
r.FormData.Set(k, v)
}
return r
}
// SetFormDataAnyType set the form data from a map, which value could be any type,
// will convert to string automatically.
// It will not been used if request method does not allow payload.
func (r *Request) SetFormDataAnyType(data map[string]interface{}) *Request {
if r.FormData == nil {
r.FormData = urlpkg.Values{}
}
for k, v := range data {
r.FormData.Set(k, fmt.Sprint(v))
}
return r
}
// SetCookies set http cookies for the request.
func (r *Request) SetCookies(cookies ...*http.Cookie) *Request {
r.Cookies = append(r.Cookies, cookies...)
return r
}
// SetQueryString set URL query parameters for the request using
// raw query string.
func (r *Request) SetQueryString(query string) *Request {
params, err := urlpkg.ParseQuery(strings.TrimSpace(query))
if err != nil {
r.client.log.Warnf("failed to parse query string (%s): %v", query, err)
return r
}
if r.QueryParams == nil {
r.QueryParams = make(urlpkg.Values)
}
for p, v := range params {
for _, pv := range v {
r.QueryParams.Add(p, pv)
}
}
return r
}
// SetFileReader set up a multipart form with a reader to upload file.
func (r *Request) SetFileReader(paramName, filename string, reader io.Reader) *Request {
r.SetFileUpload(FileUpload{
ParamName: paramName,
FileName: filename,
GetFileContent: func() (io.ReadCloser, error) {
if rc, ok := reader.(io.ReadCloser); ok {
return rc, nil
}
return io.NopCloser(reader), nil
},
})
return r
}
// SetFileBytes set up a multipart form with given []byte to upload.
func (r *Request) SetFileBytes(paramName, filename string, content []byte) *Request {
r.SetFileUpload(FileUpload{
ParamName: paramName,
FileName: filename,
GetFileContent: func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(content)), nil
},
})
return r
}
// SetFiles set up a multipart form from a map to upload, which
// key is the parameter name, and value is the file path.
func (r *Request) SetFiles(files map[string]string) *Request {
for k, v := range files {
r.SetFile(k, v)
}
return r
}
// SetFile set up a multipart form from file path to upload,
// which read file from filePath automatically to upload.
func (r *Request) SetFile(paramName, filePath string) *Request {
file, err := os.Open(filePath)
if err != nil {
r.client.log.Errorf("failed to open %s: %v", filePath, err)
r.appendError(err)
return r
}
fileInfo, err := os.Stat(filePath)
if err != nil {
r.client.log.Errorf("failed to stat file %s: %v", filePath, err)
r.appendError(err)
return r
}
r.isMultiPart = true
return r.SetFileUpload(FileUpload{
ParamName: paramName,
FileName: filepath.Base(filePath),
GetFileContent: func() (io.ReadCloser, error) {
if r.RetryAttempt > 0 {
file, err = os.Open(filePath)
if err != nil {
return nil, err
}
}
return file, nil
},
FileSize: fileInfo.Size(),
})
}
var (
errMissingParamName = errors.New("missing param name in multipart file upload")
errMissingFileName = errors.New("missing filename in multipart file upload")
errMissingFileContent = errors.New("missing file content in multipart file upload")
)
// SetFileUpload set the fully custimized multipart file upload options.
func (r *Request) SetFileUpload(uploads ...FileUpload) *Request {
r.isMultiPart = true
for _, upload := range uploads {
shouldAppend := true
if upload.ParamName == "" {
r.appendError(errMissingParamName)
shouldAppend = false
}
if upload.FileName == "" {
r.appendError(errMissingFileName)
shouldAppend = false
}
if upload.GetFileContent == nil {
r.appendError(errMissingFileContent)
shouldAppend = false
}
if shouldAppend {
r.uploadFiles = append(r.uploadFiles, &upload)
}
}
return r
}
// SetUploadCallback set the UploadCallback which will be invoked at least
// every 200ms during file upload, usually used to show upload progress.
func (r *Request) SetUploadCallback(callback UploadCallback) *Request {
return r.SetUploadCallbackWithInterval(callback, 200*time.Millisecond)
}
// SetUploadCallbackWithInterval set the UploadCallback which will be invoked at least
// every `minInterval` during file upload, usually used to show upload progress.
func (r *Request) SetUploadCallbackWithInterval(callback UploadCallback, minInterval time.Duration) *Request {
if callback == nil {
return r
}
r.forceChunkedEncoding = true
r.uploadCallback = callback
r.uploadCallbackInterval = minInterval
return r
}
// SetDownloadCallback set the DownloadCallback which will be invoked at least
// every 200ms during file upload, usually used to show download progress.
func (r *Request) SetDownloadCallback(callback DownloadCallback) *Request {
return r.SetDownloadCallbackWithInterval(callback, 200*time.Millisecond)
}
// SetDownloadCallbackWithInterval set the DownloadCallback which will be invoked at least
// every `minInterval` during file upload, usually used to show download progress.
func (r *Request) SetDownloadCallbackWithInterval(callback DownloadCallback, minInterval time.Duration) *Request {
if callback == nil {
return r
}
r.downloadCallback = callback
r.downloadCallbackInterval = minInterval
return r
}
// SetResult set the result that response Body will be unmarshalled to if
// no error occurs and Response.ResultState() returns SuccessState, by default
// it requires HTTP status `code >= 200 && code <= 299`, you can also use
// Request.SetResultStateCheckFunc or Client.SetResultStateCheckFunc to customize
// the result state check logic.
//
// Deprecated: Use SetSuccessResult instead.
func (r *Request) SetResult(result interface{}) *Request {
return r.SetSuccessResult(result)
}
// SetSuccessResult set the result that response Body will be unmarshalled to if
// no error occurs and Response.ResultState() returns SuccessState, by default
// it requires HTTP status `code >= 200 && code <= 299`, you can also use
// Request.SetResultStateCheckFunc or Client.SetResultStateCheckFunc to customize
// the result state check logic.
func (r *Request) SetSuccessResult(result interface{}) *Request {
if result == nil {
return r
}
r.Result = util.GetPointer(result)
return r
}
// SetError set the result that response body will be unmarshalled to if
// no error occurs and Response.ResultState() returns ErrorState, by default
// it requires HTTP status `code >= 400`, you can also use Request.SetResultStateCheckFunc
// or Client.SetResultStateCheckFunc to customize the result state check logic.
//
// Deprecated: Use SetErrorResult result.
func (r *Request) SetError(err interface{}) *Request {
return r.SetErrorResult(err)
}
// SetErrorResult set the result that response body will be unmarshalled to if
// no error occurs and Response.ResultState() returns ErrorState, by default
// it requires HTTP status `code >= 400`, you can also use Request.SetResultStateCheckFunc
// or Client.SetResultStateCheckFunc to customize the result state check logic.
func (r *Request) SetErrorResult(err interface{}) *Request {
if err == nil {
return r
}
r.Error = util.GetPointer(err)
return r
}
// SetBearerAuthToken set bearer auth token for the request.
func (r *Request) SetBearerAuthToken(token string) *Request {
return r.SetHeader(header.Authorization, "Bearer "+token)
}
// SetBasicAuth set basic auth for the request.
func (r *Request) SetBasicAuth(username, password string) *Request {
return r.SetHeader(header.Authorization, util.BasicAuthHeaderValue(username, password))
}
// SetDigestAuth sets the Digest Access auth scheme for the HTTP request. If a server responds with 401 and sends a
// Digest challenge in the WWW-Authenticate Header, the request will be resent with the appropriate Authorization Header.
//
// For Example: To set the Digest scheme with username "roc" and password "123456"
//
// client.R().SetDigestAuth("roc", "123456")
//
// Information about Digest Access Authentication can be found in RFC7616:
//
// https://datatracker.ietf.org/doc/html/rfc7616
//
// This method overrides the username and password set by method `Client.SetCommonDigestAuth`.
func (r *Request) SetDigestAuth(username, password string) *Request {
r.OnAfterResponse(handleDigestAuthFunc(username, password))
return r
}
// OnAfterResponse add a response middleware which hooks after response received.
func (r *Request) OnAfterResponse(m ResponseMiddleware) *Request {
r.afterResponse = append(r.afterResponse, m)
return r
}
// SetHeaders set headers from a map for the request.
func (r *Request) SetHeaders(hdrs map[string]string) *Request {
for k, v := range hdrs {
r.SetHeader(k, v)
}
return r
}
// SetHeader set a header for the request.
func (r *Request) SetHeader(key, value string) *Request {
if r.Headers == nil {
r.Headers = make(http.Header)
}
r.Headers.Set(key, value)
return r
}
// SetHeadersNonCanonical set headers from a map for the request which key is a
// non-canonical key (keep case unchanged), only valid for HTTP/1.1.
func (r *Request) SetHeadersNonCanonical(hdrs map[string]string) *Request {
for k, v := range hdrs {
r.SetHeaderNonCanonical(k, v)
}
return r
}
// SetHeaderNonCanonical set a header for the request which key is a
// non-canonical key (keep case unchanged), only valid for HTTP/1.1.
func (r *Request) SetHeaderNonCanonical(key, value string) *Request {
if r.Headers == nil {
r.Headers = make(http.Header)
}
r.Headers[key] = append(r.Headers[key], value)
return r
}
const (
// HeaderOderKey is the key of header order, which specifies the order
// of the http header.
HeaderOderKey = "__header_order__"
// PseudoHeaderOderKey is the key of pseudo header order, which specifies
// the order of the http2 and http3 pseudo header.
PseudoHeaderOderKey = "__pseudo_header_order__"
)
// SetHeaderOrder set the order of the http header (case-insensitive).
// For example:
//
// client.R().SetHeaderOrder(
// "custom-header",
// "cookie",
// "user-agent",
// "accept-encoding",
// )
func (r *Request) SetHeaderOrder(keys ...string) *Request {
if r.Headers == nil {
r.Headers = make(http.Header)
}
r.Headers[HeaderOderKey] = append(r.Headers[HeaderOderKey], keys...)
return r
}
// SetPseudoHeaderOrder set the order of the pseudo http header (case-insensitive).
// Note this is only valid for http2 and http3.
// For example:
//
// client.R().SetPseudoHeaderOrder(
// ":scheme",
// ":authority",
// ":path",
// ":method",
// )
func (r *Request) SetPseudoHeaderOrder(keys ...string) *Request {
if r.Headers == nil {
r.Headers = make(http.Header)
}
r.Headers[PseudoHeaderOderKey] = append(r.Headers[PseudoHeaderOderKey], keys...)
return r
}
// SetOutputFile set the file that response Body will be downloaded to.
func (r *Request) SetOutputFile(file string) *Request {
r.isSaveResponse = true
r.outputFile = file
return r
}
// SetOutput set the io.Writer that response Body will be downloaded to.
func (r *Request) SetOutput(output io.Writer) *Request {
if output == nil {
r.client.log.Warnf("nil io.Writer is not allowed in SetOutput")
return r
}
r.output = output
r.isSaveResponse = true
return r
}
// SetQueryParams set URL query parameters from a map for the request.
func (r *Request) SetQueryParams(params map[string]string) *Request {
for k, v := range params {
r.SetQueryParam(k, v)
}
return r
}
// SetQueryParamsAnyType set URL query parameters from a map for the request.
// The value of map is any type, will be convert to string automatically.
func (r *Request) SetQueryParamsAnyType(params map[string]interface{}) *Request {
for k, v := range params {
r.SetQueryParam(k, fmt.Sprint(v))
}
return r
}
// SetQueryParam set an URL query parameter for the request.
func (r *Request) SetQueryParam(key, value string) *Request {
if r.QueryParams == nil {
r.QueryParams = make(urlpkg.Values)
}
r.QueryParams.Set(key, value)
return r
}
// AddQueryParam add a URL query parameter for the request.
func (r *Request) AddQueryParam(key, value string) *Request {
if r.QueryParams == nil {
r.QueryParams = make(urlpkg.Values)
}
r.QueryParams.Add(key, value)
return r
}
// AddQueryParams add one or more values of specified URL query parameter for the request.
func (r *Request) AddQueryParams(key string, values ...string) *Request {
if r.QueryParams == nil {
r.QueryParams = make(urlpkg.Values)
}
vs := r.QueryParams[key]
vs = append(vs, values...)
r.QueryParams[key] = vs
return r
}
// SetPathParams set URL path parameters from a map for the request.
func (r *Request) SetPathParams(params map[string]string) *Request {
for key, value := range params {
r.SetPathParam(key, value)
}
return r
}
// SetPathParam set a URL path parameter for the request.
func (r *Request) SetPathParam(key, value string) *Request {
if r.PathParams == nil {
r.PathParams = make(map[string]string)
}
r.PathParams[key] = value
return r
}
func (r *Request) appendError(err error) {
r.error = multierror.Append(r.error, err)
}
var errRetryableWithUnReplayableBody = errors.New("retryable request should not have unreplayable Body (io.Reader)")
func (r *Request) newErrorResponse(err error) *Response {
resp := &Response{Request: r}
resp.Err = err
return resp
}
// Do fires http request, 0 or 1 context is allowed, and returns the *Response which
// is always not nil, and Response.Err is not nil if error occurs.
func (r *Request) Do(ctx ...context.Context) *Response {
if len(ctx) > 0 && ctx[0] != nil {
r.ctx = ctx[0]
}
defer func() {
r.responseReturnTime = time.Now()
}()
if r.error != nil {
return r.newErrorResponse(r.error)
}
if r.retryOption != nil && r.retryOption.MaxRetries != 0 && r.unReplayableBody != nil { // retryable request should not have unreplayable Body
return r.newErrorResponse(errRetryableWithUnReplayableBody)
}
resp, _ := r.do()
return resp
}
func (r *Request) do() (resp *Response, err error) {
defer func() {
if resp == nil {
resp = &Response{Request: r}
}
if err != nil {
resp.Err = err
}
}()
for {
if r.Headers == nil {
r.Headers = make(http.Header)
}
for _, f := range r.client.udBeforeRequest {
if err = f(r.client, r); err != nil {
return
}
}
for _, f := range r.client.beforeRequest {
if err = f(r.client, r); err != nil {
return
}
}
if r.client.wrappedRoundTrip != nil {
resp, err = r.client.wrappedRoundTrip.RoundTrip(r)
} else {
resp, err = r.client.roundTrip(r)
}
for _, f := range r.afterResponse {
if err = f(r.client, resp); err != nil {
return
}
}
if r.retryOption == nil || (r.RetryAttempt >= r.retryOption.MaxRetries && r.retryOption.MaxRetries >= 0) { // absolutely cannot retry.
return
}
// check retry whether is needed.
needRetry := err != nil // default behaviour: retry if error occurs
if l := len(r.retryOption.RetryConditions); l > 0 { // override default behaviour if custom RetryConditions has been set.
for i := l - 1; i >= 0; i-- {
needRetry = r.retryOption.RetryConditions[i](resp, err)
if needRetry {
break
}
}
}
if !needRetry { // no retry is needed.
return
}
// need retry, attempt to retry
r.RetryAttempt++
if l := len(r.retryOption.RetryHooks); l > 0 {
for i := l - 1; i >= 0; i-- { // run retry hooks in reverse order
r.retryOption.RetryHooks[i](resp, err)
}
}
time.Sleep(r.retryOption.GetRetryInterval(resp, r.RetryAttempt))
// clean up before retry
if r.dumpBuffer != nil {
r.dumpBuffer.Reset()
}
if r.trace != nil {
r.trace = &clientTrace{}
}
resp.body = nil
resp.result = nil
resp.error = nil
}
}
// Send fires http request with specified method and url, returns the
// *Response which is always not nil, and the error is not nil if error occurs.
func (r *Request) Send(method, url string) (*Response, error) {
r.Method = method
r.RawURL = url
resp := r.Do()
if resp.Err != nil && r.client.onError != nil {
r.client.onError(r.client, r, resp, resp.Err)
}
return resp, resp.Err
}
// MustGet like Get, panic if error happens, should only be used to
// test without error handling.
func (r *Request) MustGet(url string) *Response {
resp, err := r.Get(url)
if err != nil {
panic(err)
}
return resp
}
// Get fires http request with GET method and the specified URL.
func (r *Request) Get(url string) (*Response, error) {
return r.Send(http.MethodGet, url)
}
// MustPost like Post, panic if error happens. should only be used to
// test without error handling.
func (r *Request) MustPost(url string) *Response {
resp, err := r.Post(url)
if err != nil {
panic(err)
}
return resp
}
// Post fires http request with POST method and the specified URL.
func (r *Request) Post(url string) (*Response, error) {
return r.Send(http.MethodPost, url)
}
// MustPut like Put, panic if error happens, should only be used to
// test without error handling.
func (r *Request) MustPut(url string) *Response {
resp, err := r.Put(url)
if err != nil {
panic(err)
}
return resp
}
// Put fires http request with PUT method and the specified URL.
func (r *Request) Put(url string) (*Response, error) {
return r.Send(http.MethodPut, url)
}
// MustPatch like Patch, panic if error happens, should only be used
// to test without error handling.
func (r *Request) MustPatch(url string) *Response {
resp, err := r.Patch(url)
if err != nil {
panic(err)
}
return resp
}
// Patch fires http request with PATCH method and the specified URL.
func (r *Request) Patch(url string) (*Response, error) {
return r.Send(http.MethodPatch, url)
}
// MustDelete like Delete, panic if error happens, should only be used
// to test without error handling.
func (r *Request) MustDelete(url string) *Response {
resp, err := r.Delete(url)
if err != nil {
panic(err)
}
return resp
}
// Delete fires http request with DELETE method and the specified URL.
func (r *Request) Delete(url string) (*Response, error) {
return r.Send(http.MethodDelete, url)
}
// MustOptions like Options, panic if error happens, should only be
// used to test without error handling.
func (r *Request) MustOptions(url string) *Response {
resp, err := r.Options(url)
if err != nil {
panic(err)
}
return resp
}
// Options fires http request with OPTIONS method and the specified URL.
func (r *Request) Options(url string) (*Response, error) {
return r.Send(http.MethodOptions, url)
}
// MustHead like Head, panic if error happens, should only be used
// to test without error handling.
func (r *Request) MustHead(url string) *Response {
resp, err := r.Send(http.MethodHead, url)
if err != nil {
panic(err)
}
return resp
}
// Head fires http request with HEAD method and the specified URL.
func (r *Request) Head(url string) (*Response, error) {
return r.Send(http.MethodHead, url)
}
// SetBody set the request Body, accepts string, []byte, io.Reader, map and struct.
func (r *Request) SetBody(body interface{}) *Request {
if body == nil {
return r
}
switch b := body.(type) {
case io.ReadCloser:
r.unReplayableBody = b
r.GetBody = func() (io.ReadCloser, error) {
return r.unReplayableBody, nil
}
case io.Reader:
r.unReplayableBody = io.NopCloser(b)
r.GetBody = func() (io.ReadCloser, error) {
return r.unReplayableBody, nil
}
case []byte:
r.SetBodyBytes(b)
case string:
r.SetBodyString(b)
case func() (io.ReadCloser, error):
r.GetBody = b
case GetContentFunc:
r.GetBody = b
default:
t := reflect.TypeOf(body)
switch t.Kind() {
case reflect.Ptr, reflect.Struct, reflect.Map, reflect.Slice, reflect.Array:
r.marshalBody = body
default:
r.SetBodyString(fmt.Sprint(body))
}
}
return r
}
// SetBodyBytes set the request Body as []byte.
func (r *Request) SetBodyBytes(body []byte) *Request {
r.Body = body
r.GetBody = func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(body)), nil
}
return r
}
// SetBodyString set the request Body as string.
func (r *Request) SetBodyString(body string) *Request {
return r.SetBodyBytes([]byte(body))
}
// SetBodyJsonString set the request Body as string and set Content-Type header
// as "application/json; charset=utf-8"
func (r *Request) SetBodyJsonString(body string) *Request {
return r.SetBodyJsonBytes([]byte(body))
}
// SetBodyJsonBytes set the request Body as []byte and set Content-Type header
// as "application/json; charset=utf-8"
func (r *Request) SetBodyJsonBytes(body []byte) *Request {
r.SetContentType(header.JsonContentType)
return r.SetBodyBytes(body)
}
// SetBodyJsonMarshal set the request Body that marshaled from object, and
// set Content-Type header as "application/json; charset=utf-8"
func (r *Request) SetBodyJsonMarshal(v interface{}) *Request {
b, err := r.client.jsonMarshal(v)
if err != nil {
r.appendError(err)
return r
}
return r.SetBodyJsonBytes(b)
}
// SetBodyXmlString set the request Body as string and set Content-Type header
// as "text/xml; charset=utf-8"
func (r *Request) SetBodyXmlString(body string) *Request {
return r.SetBodyXmlBytes([]byte(body))
}
// SetBodyXmlBytes set the request Body as []byte and set Content-Type header
// as "text/xml; charset=utf-8"
func (r *Request) SetBodyXmlBytes(body []byte) *Request {
r.SetContentType(header.XmlContentType)
return r.SetBodyBytes(body)
}
// SetBodyXmlMarshal set the request Body that marshaled from object, and
// set Content-Type header as "text/xml; charset=utf-8"
func (r *Request) SetBodyXmlMarshal(v interface{}) *Request {
b, err := r.client.xmlMarshal(v)
if err != nil {
r.appendError(err)
return r
}
return r.SetBodyXmlBytes(b)
}
// SetContentType set the `Content-Type` for the request.
func (r *Request) SetContentType(contentType string) *Request {
return r.SetHeader(header.ContentType, contentType)
}
// Context method returns the Context if its already set in request
// otherwise it creates new one using `context.Background()`.
func (r *Request) Context() context.Context {
if r.ctx == nil {
r.ctx = context.Background()
}
return r.ctx
}
// SetContext method sets the context.Context for current Request. It allows
// to interrupt the request execution if ctx.Done() channel is closed.
// See https://blog.golang.org/context article and the "context" package
// documentation.
//
// Attention: make sure call SetContext before EnableDumpXXX if you want to
// dump at the request level.
func (r *Request) SetContext(ctx context.Context) *Request {
if ctx != nil {
r.ctx = ctx
}
return r
}
// DisableAutoReadResponse disable read response body automatically (enabled by default).
func (r *Request) DisableAutoReadResponse() *Request {
r.disableAutoReadResponse = true
return r
}
// EnableAutoReadResponse enable read response body automatically (enabled by default).
func (r *Request) EnableAutoReadResponse() *Request {
r.disableAutoReadResponse = false
return r
}
// DisableTrace disables trace.
func (r *Request) DisableTrace() *Request {
r.trace = nil
return r
}
// EnableTrace enables trace (http3 currently does not support trace).
func (r *Request) EnableTrace() *Request {
if r.trace == nil {
r.trace = &clientTrace{}
}
return r
}
func (r *Request) getDumpBuffer() *bytes.Buffer {
if r.dumpBuffer == nil {
r.dumpBuffer = new(bytes.Buffer)
}
return r.dumpBuffer
}
func (r *Request) getDumpOptions() *DumpOptions {
if r.dumpOptions == nil {
r.dumpOptions = &DumpOptions{
RequestHeader: true,
RequestBody: true,
ResponseHeader: true,
ResponseBody: true,
Output: r.getDumpBuffer(),
}
}
return r.dumpOptions
}
// EnableDumpTo enables dump and save to the specified io.Writer.
func (r *Request) EnableDumpTo(output io.Writer) *Request {