-
-
Notifications
You must be signed in to change notification settings - Fork 724
/
Copy pathrequest.go
1784 lines (1623 loc) · 54.2 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
// 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"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"maps"
"mime/multipart"
"net"
"net/http"
"net/url"
"path/filepath"
"reflect"
"strings"
"syscall"
"time"
)
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Request struct and methods
//_______________________________________________________________________
// Request struct is used to compose and fire individual requests from
// Resty client. The [Request] provides an option to override client-level
// settings and also an option for the request composition.
type Request struct {
URL string
Method string
AuthToken string
AuthScheme string
QueryParams url.Values
FormData url.Values
PathParams map[string]string
Header http.Header
Time time.Time
Body any
Result any
Error any
RawRequest *http.Request
Cookies []*http.Cookie
Debug bool
CloseConnection bool
DoNotParseResponse bool
OutputFileName string
ExpectResponseContentType string
ForceResponseContentType string
DebugBodyLimit int
ResponseBodyLimit int64
ResponseBodyUnlimitedReads bool
IsTrace bool
AllowMethodGetPayload bool
AllowMethodDeletePayload bool
IsDone bool
IsSaveResponse bool
Timeout time.Duration
HeaderAuthorizationKey string
RetryCount int
RetryWaitTime time.Duration
RetryMaxWaitTime time.Duration
RetryStrategy RetryStrategyFunc
IsRetryDefaultConditions bool
AllowNonIdempotentRetry bool
// RetryTraceID provides GUID for retry count > 0
RetryTraceID string
// Attempt provides insights into no. of attempts
// Resty made.
//
// first attempt + retry count = total attempts
Attempt int
credentials *credentials
isMultiPart bool
isFormData bool
setContentLength bool
jsonEscapeHTML bool
ctx context.Context
ctxCancelFunc context.CancelFunc
values map[string]any
client *Client
bodyBuf *bytes.Buffer
trace *clientTrace
log Logger
baseURL string
multipartBoundary string
multipartFields []*MultipartField
retryConditions []RetryConditionFunc
retryHooks []RetryHookFunc
resultCurlCmd string
generateCurlCmd bool
debugLogCurlCmd bool
unescapeQueryParams bool
multipartErrChan chan error
}
// SetMethod method used to set the HTTP verb for the request
func (r *Request) SetMethod(m string) *Request {
r.Method = m
return r
}
// SetURL method used to set the request URL for the request
func (r *Request) SetURL(url string) *Request {
r.URL = url
return r
}
// Context method returns the request's [context.Context]. To change the context, use
// [Request.Clone] or [Request.WithContext].
//
// The returned context is always non-nil; it defaults to the
// background context.
func (r *Request) Context() context.Context {
if r.ctx == nil {
return context.Background()
}
return r.ctx
}
// SetContext method sets the [context.Context] for current [Request].
// It overwrites the current context in the Request instance; it does not
// affect the [Request].RawRequest that was already created.
//
// If you want this method to take effect, use this method before invoking
// [Request.Send] or [Request].HTTPVerb methods.
//
// See [Request.WithContext], [Request.Clone]
func (r *Request) SetContext(ctx context.Context) *Request {
r.ctx = ctx
return r
}
// WithContext method returns a shallow copy of r with its context changed
// to ctx. The provided ctx must be non-nil. It does not
// affect the [Request].RawRequest that was already created.
//
// If you want this method to take effect, use this method before invoking
// [Request.Send] or [Request].HTTPVerb methods.
//
// See [Request.SetContext], [Request.Clone]
func (r *Request) WithContext(ctx context.Context) *Request {
if ctx == nil {
panic("resty: Request.WithContext nil context")
}
rr := new(Request)
*rr = *r
rr.ctx = ctx
return rr
}
// SetContentType method is a convenient way to set the header Content-Type in the request
//
// client.R().SetContentType("application/json")
func (r *Request) SetContentType(ct string) *Request {
r.SetHeader(hdrContentTypeKey, ct)
return r
}
// SetHeader method sets a single header field and its value in the current request.
//
// For Example: To set `Content-Type` and `Accept` as `application/json`.
//
// client.R().
// SetHeader("Content-Type", "application/json").
// SetHeader("Accept", "application/json")
//
// It overrides the header value set at the client instance level.
func (r *Request) SetHeader(header, value string) *Request {
r.Header.Set(header, value)
return r
}
// SetHeaders method sets multiple header fields and their values at one go in the current request.
//
// For Example: To set `Content-Type` and `Accept` as `application/json`
//
// client.R().
// SetHeaders(map[string]string{
// "Content-Type": "application/json",
// "Accept": "application/json",
// })
//
// It overrides the header value set at the client instance level.
func (r *Request) SetHeaders(headers map[string]string) *Request {
for h, v := range headers {
r.SetHeader(h, v)
}
return r
}
// SetHeaderMultiValues sets multiple header fields and their values as a list of strings in the current request.
//
// For Example: To set `Accept` as `text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, */*;q=0.8`
//
// client.R().
// SetHeaderMultiValues(map[string][]string{
// "Accept": []string{"text/html", "application/xhtml+xml", "application/xml;q=0.9", "image/webp", "*/*;q=0.8"},
// })
//
// It overrides the header value set at the client instance level.
func (r *Request) SetHeaderMultiValues(headers map[string][]string) *Request {
for key, values := range headers {
r.SetHeader(key, strings.Join(values, ", "))
}
return r
}
// 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.R().
// SetHeaderVerbatim("all_lowercase", "available").
// SetHeaderVerbatim("UPPERCASE", "available").
// SetHeaderVerbatim("x-cloud-trace-id", "798e94019e5fc4d57fbb8901eb4c6cae")
//
// It overrides the header value set at the client instance level.
func (r *Request) SetHeaderVerbatim(header, value string) *Request {
r.Header[header] = []string{value}
return r
}
// SetQueryParam method sets a single parameter and its value in the current request.
// It will be formed as a query string for the request.
//
// For Example: `search=kitchen%20papers&size=large` in the URL after the `?` mark.
//
// client.R().
// SetQueryParam("search", "kitchen papers").
// SetQueryParam("size", "large")
//
// It overrides the query parameter value set at the client instance level.
func (r *Request) SetQueryParam(param, value string) *Request {
r.QueryParams.Set(param, value)
return r
}
// SetQueryParams method sets multiple parameters and their values at one go in the current request.
// It will be formed as a query string for the request.
//
// For Example: `search=kitchen%20papers&size=large` in the URL after the `?` mark.
//
// client.R().
// SetQueryParams(map[string]string{
// "search": "kitchen papers",
// "size": "large",
// })
//
// It overrides the query parameter value set at the client instance level.
func (r *Request) SetQueryParams(params map[string]string) *Request {
for p, v := range params {
r.SetQueryParam(p, v)
}
return r
}
// SetQueryParamsFromValues method appends multiple parameters with multi-value
// ([url.Values]) at one go in the current request. It will be formed as
// query string for the request.
//
// For Example: `status=pending&status=approved&status=open` in the URL after the `?` mark.
//
// client.R().
// SetQueryParamsFromValues(url.Values{
// "status": []string{"pending", "approved", "open"},
// })
//
// It overrides the query parameter value set at the client instance level.
func (r *Request) SetQueryParamsFromValues(params url.Values) *Request {
for p, v := range params {
for _, pv := range v {
r.QueryParams.Add(p, pv)
}
}
return r
}
// SetQueryString method provides the ability to use string as an input to set URL query string for the request.
//
// client.R().
// SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more")
//
// It overrides the query parameter value set at the client instance level.
func (r *Request) SetQueryString(query string) *Request {
params, err := url.ParseQuery(strings.TrimSpace(query))
if err == nil {
for p, v := range params {
for _, pv := range v {
r.QueryParams.Add(p, pv)
}
}
} else {
r.log.Errorf("%v", err)
}
return r
}
// SetFormData method sets form parameters and their values in the current request.
// The request content type would be set as `application/x-www-form-urlencoded`.
//
// client.R().
// SetFormData(map[string]string{
// "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F",
// "user_id": "3455454545",
// })
//
// It overrides the form data value set at the client instance level.
//
// See [Request.SetFormDataFromValues] for the same field name with multiple values.
func (r *Request) SetFormData(data map[string]string) *Request {
for k, v := range data {
r.FormData.Set(k, v)
}
return r
}
// SetFormDataFromValues method appends multiple form parameters with multi-value
// ([url.Values]) at one go in the current request.
//
// client.R().
// SetFormDataFromValues(url.Values{
// "search_criteria": []string{"book", "glass", "pencil"},
// })
//
// It overrides the form data value set at the client instance level.
func (r *Request) SetFormDataFromValues(data url.Values) *Request {
for k, v := range data {
for _, kv := range v {
r.FormData.Add(k, kv)
}
}
return r
}
// SetBody method sets the request body for the request. It supports various practical needs as easy.
// It's quite handy and powerful. Supported request body data types are `string`,
// `[]byte`, `struct`, `map`, `slice` and [io.Reader].
//
// Body value can be pointer or non-pointer. Automatic marshalling for JSON and XML content type, if it is `struct`, `map`, or `slice`.
//
// NOTE: [io.Reader] is processed in bufferless mode while sending a request.
//
// For Example:
//
// `struct` gets marshaled based on the request header `Content-Type`.
//
// client.R().
// SetBody(User{
// Username: "[email protected]",
// Password: "welcome2resty",
// })
//
// 'map` gets marshaled based on the request header `Content-Type`.
//
// client.R().
// SetBody(map[string]any{
// "username": "[email protected]",
// "password": "welcome2resty",
// "address": &Address{
// Address1: "1111 This is my street",
// Address2: "Apt 201",
// City: "My City",
// State: "My State",
// ZipCode: 00000,
// },
// })
//
// `string` as a body input. Suitable for any need as a string input.
//
// client.R().
// SetBody(`{
// "username": "[email protected]",
// "password": "admin"
// }`)
//
// `[]byte` as a body input. Suitable for raw requests such as file upload, serialize & deserialize, etc.
//
// client.R().
// SetBody([]byte("This is my raw request, sent as-is"))
//
// and so on.
func (r *Request) SetBody(body any) *Request {
r.Body = body
return r
}
// SetResult method is to register the response `Result` object for automatic
// unmarshalling of the HTTP response if the response status code is
// between 200 and 299, and the content type is JSON or XML.
//
// Note: [Request.SetResult] input can be a pointer or non-pointer.
//
// The pointer with handle
//
// authToken := &AuthToken{}
// client.R().SetResult(authToken)
//
// // Can be accessed via -
// fmt.Println(authToken) OR fmt.Println(response.Result().(*AuthToken))
//
// OR -
//
// The pointer without handle or non-pointer
//
// client.R().SetResult(&AuthToken{})
// // OR
// client.R().SetResult(AuthToken{})
//
// // Can be accessed via -
// fmt.Println(response.Result().(*AuthToken))
func (r *Request) SetResult(v any) *Request {
r.Result = getPointer(v)
return r
}
// SetError method is to register the request `Error` object for automatic unmarshalling for the request,
// if the response status code is greater than 399 and the content type is either JSON or XML.
//
// NOTE: [Request.SetError] input can be a pointer or non-pointer.
//
// client.R().SetError(&AuthError{})
// // OR
// client.R().SetError(AuthError{})
//
// Accessing an error value from response instance.
//
// response.Error().(*AuthError)
//
// If this request Error object is nil, Resty will use the client-level error object Type if it is set.
func (r *Request) SetError(err any) *Request {
r.Error = getPointer(err)
return r
}
// SetFile method sets a single file field name and its path for multipart upload.
//
// Resty provides an optional multipart live upload progress callback;
// see method [Request.SetMultipartFields]
//
// client.R().
// SetFile("my_file", "/Users/jeeva/Gas Bill - Sep.pdf")
func (r *Request) SetFile(fieldName, filePath string) *Request {
r.isMultiPart = true
r.multipartFields = append(r.multipartFields, &MultipartField{
Name: fieldName,
FileName: filepath.Base(filePath),
FilePath: filePath,
})
return r
}
// SetFiles method sets multiple file field names and their paths for multipart uploads.
//
// Resty provides an optional multipart live upload progress callback;
// see method [Request.SetMultipartFields]
//
// client.R().
// SetFiles(map[string]string{
// "my_file1": "/Users/jeeva/Gas Bill - Sep.pdf",
// "my_file2": "/Users/jeeva/Electricity Bill - Sep.pdf",
// "my_file3": "/Users/jeeva/Water Bill - Sep.pdf",
// })
func (r *Request) SetFiles(files map[string]string) *Request {
r.isMultiPart = true
for f, fp := range files {
r.multipartFields = append(r.multipartFields, &MultipartField{
Name: f,
FileName: filepath.Base(fp),
FilePath: fp,
})
}
return r
}
// SetFileReader method is to set a file using [io.Reader] for multipart upload.
//
// Resty provides an optional multipart live upload progress callback;
// see method [Request.SetMultipartFields]
//
// client.R().
// SetFileReader("profile_img", "my-profile-img.png", bytes.NewReader(profileImgBytes)).
// SetFileReader("notes", "user-notes.txt", bytes.NewReader(notesBytes))
func (r *Request) SetFileReader(fieldName, fileName string, reader io.Reader) *Request {
r.SetMultipartField(fieldName, fileName, "", reader)
return r
}
// SetMultipartFormData method allows simple form data to be attached to the request
// as `multipart:form-data`
func (r *Request) SetMultipartFormData(data map[string]string) *Request {
r.isMultiPart = true
for k, v := range data {
r.FormData.Set(k, v)
}
return r
}
// SetMultipartOrderedFormData method allows add ordered form data to be attached to the request
// as `multipart:form-data`
func (r *Request) SetMultipartOrderedFormData(name string, values []string) *Request {
r.isMultiPart = true
r.multipartFields = append(r.multipartFields, &MultipartField{
Name: name,
Values: values,
})
return r
}
// SetMultipartField method sets custom data with Content-Type using [io.Reader] for multipart upload.
//
// Resty provides an optional multipart live upload progress callback;
// see method [Request.SetMultipartFields]
func (r *Request) SetMultipartField(fieldName, fileName, contentType string, reader io.Reader) *Request {
r.isMultiPart = true
r.multipartFields = append(r.multipartFields, &MultipartField{
Name: fieldName,
FileName: fileName,
ContentType: contentType,
Reader: reader,
})
return r
}
// SetMultipartFields method sets multiple data fields using [io.Reader] for multipart upload.
//
// Resty provides an optional multipart live upload progress count in bytes; see
// [MultipartField].ProgressCallback and [MultipartFieldProgress]
//
// For Example:
//
// client.R().SetMultipartFields(
// &resty.MultipartField{
// Name: "uploadManifest1",
// FileName: "upload-file-1.json",
// ContentType: "application/json",
// Reader: strings.NewReader(`{"input": {"name": "Uploaded document 1", "_filename" : ["file1.txt"]}}`),
// },
// &resty.MultipartField{
// Name: "uploadManifest2",
// FileName: "upload-file-2.json",
// ContentType: "application/json",
// FilePath: "/path/to/upload-file-2.json",
// },
// &resty.MultipartField{
// Name: "image-file1",
// FileName: "image-file1.png",
// ContentType: "image/png",
// Reader: bytes.NewReader(fileBytes),
// ProgressCallback: func(mp MultipartFieldProgress) {
// // use the progress details
// },
// },
// &resty.MultipartField{
// Name: "image-file2",
// FileName: "image-file2.png",
// ContentType: "image/png",
// Reader: imageFile2, // instance of *os.File
// ProgressCallback: func(mp MultipartFieldProgress) {
// // use the progress details
// },
// })
//
// If you have a `slice` of fields already, then call-
//
// client.R().SetMultipartFields(fields...)
func (r *Request) SetMultipartFields(fields ...*MultipartField) *Request {
r.isMultiPart = true
r.multipartFields = append(r.multipartFields, fields...)
return r
}
// SetMultipartBoundary method sets the custom multipart boundary for the multipart request.
// Typically, the `mime/multipart` package generates a random multipart boundary if not provided.
func (r *Request) SetMultipartBoundary(boundary string) *Request {
r.multipartBoundary = boundary
return r
}
// SetContentLength method sets the current request's HTTP header `Content-Length` value.
// By default, Resty won't set `Content-Length`.
//
// See [Client.SetContentLength]
//
// client.R().SetContentLength(true)
//
// It overrides the value set at the client instance level.
func (r *Request) SetContentLength(l bool) *Request {
r.setContentLength = l
return r
}
// SetBasicAuth method sets the basic authentication header in the current HTTP request.
//
// For Example:
//
// Authorization: Basic <base64-encoded-value>
//
// To set the header for username "go-resty" and password "welcome"
//
// client.R().SetBasicAuth("go-resty", "welcome")
//
// It overrides the credentials set by method [Client.SetBasicAuth].
func (r *Request) SetBasicAuth(username, password string) *Request {
r.credentials = &credentials{Username: username, Password: password}
return r
}
// SetAuthToken method sets the auth token header(Default Scheme: Bearer) in the current HTTP request. Header example:
//
// Authorization: Bearer <auth-token-value-comes-here>
//
// For Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F
//
// client.R().SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F")
//
// It overrides the Auth token set by method [Client.SetAuthToken].
func (r *Request) SetAuthToken(authToken string) *Request {
r.AuthToken = authToken
return r
}
// SetAuthScheme method sets the auth token scheme type in the HTTP request.
//
// Example Header value structure:
//
// Authorization: <auth-scheme-value-set-here> <auth-token-value>
//
// For Example: To set the scheme to use OAuth
//
// client.R().SetAuthScheme("OAuth")
//
// // The outcome will be -
// Authorization: OAuth <auth-token-value>
//
// Information about Auth schemes can be found in [RFC 7235], IANA [HTTP Auth schemes]
//
// It overrides the `Authorization` scheme set by method [Client.SetAuthScheme].
//
// [RFC 7235]: https://tools.ietf.org/html/rfc7235
// [HTTP Auth schemes]: https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes
func (r *Request) SetAuthScheme(scheme string) *Request {
r.AuthScheme = scheme
return r
}
// SetHeaderAuthorizationKey method sets the given HTTP header name for Authorization in the request.
//
// It overrides the `Authorization` header name set by method [Client.SetHeaderAuthorizationKey].
//
// client.R().SetHeaderAuthorizationKey("X-Custom-Authorization")
func (r *Request) SetHeaderAuthorizationKey(k string) *Request {
r.HeaderAuthorizationKey = k
return r
}
// SetOutputFileName method sets the output file for the current HTTP request. The current
// HTTP response will be saved in the given file. It is similar to the `curl -o` flag.
//
// Absolute path or relative path can be used.
//
// If it is a relative path, then the output file goes under the output directory, as mentioned
// in the [Client.SetOutputDirectory].
//
// client.R().
// SetOutputFileName("/Users/jeeva/Downloads/ReplyWithHeader-v5.1-beta.zip").
// Get("http://bit.ly/1LouEKr")
//
// NOTE: In this scenario
// - [Response.BodyBytes] might be nil.
// - [Response].Body might have been already read.
func (r *Request) SetOutputFileName(file string) *Request {
r.OutputFileName = file
r.SetSaveResponse(true)
return r
}
// SetSaveResponse method used to enable the save response option for the current requests
//
// client.R().SetSaveResponse(true)
//
// Resty determines the save filename in the following order -
// - [Request.SetOutputFileName]
// - Content-Disposition header
// - Request URL using [path.Base]
// - Request URL hostname if path is empty or "/"
//
// It overrides the value set at the client instance level, see [Client.SetSaveResponse]
func (r *Request) SetSaveResponse(save bool) *Request {
r.IsSaveResponse = save
return r
}
// SetCloseConnection method sets variable `Close` in HTTP request struct with the given
// value. More info: https://golang.org/src/net/http/request.go
//
// It overrides the value set at the client instance level, see [Client.SetCloseConnection]
func (r *Request) SetCloseConnection(close bool) *Request {
r.CloseConnection = close
return r
}
// SetDoNotParseResponse method instructs Resty not to parse the response body automatically.
//
// Resty exposes the raw response body as [io.ReadCloser]. If you use it, do not
// forget to close the body, otherwise, you might get into connection leaks, and connection
// reuse may not happen.
//
// NOTE: The default [Response] middlewares are not executed when using this option. User
// takes over the control of handling response body from Resty.
func (r *Request) SetDoNotParseResponse(notParse bool) *Request {
r.DoNotParseResponse = notParse
return r
}
// SetResponseBodyLimit method sets a maximum body size limit in bytes on response,
// avoid reading too much data to memory.
//
// Client will return [resty.ErrResponseBodyTooLarge] if the body size of the body
// in the uncompressed response is larger than the limit.
// Body size limit will not be enforced in the following cases:
// - ResponseBodyLimit <= 0, which is the default behavior.
// - [Request.SetOutputFileName] is called to save response data to the file.
// - "DoNotParseResponse" is set for client or request.
//
// It overrides the value set at the client instance level, see [Client.SetResponseBodyLimit]
func (r *Request) SetResponseBodyLimit(v int64) *Request {
r.ResponseBodyLimit = v
return r
}
// SetResponseBodyUnlimitedReads method is to turn on/off the response body in memory
// that provides an ability to do unlimited reads.
//
// It overrides the value set at the client level; see [Client.SetResponseBodyUnlimitedReads]
//
// Unlimited reads are possible in a few scenarios, even without enabling it.
// - When debug mode is enabled
//
// NOTE: Use with care
// - Turning on this feature keeps the response body in memory, which might cause additional memory usage.
func (r *Request) SetResponseBodyUnlimitedReads(b bool) *Request {
r.ResponseBodyUnlimitedReads = b
return r
}
// SetPathParam method sets a single URL path key-value pair in the
// Resty current request instance.
//
// client.R().SetPathParam("userId", "[email protected]")
//
// Result:
// URL - /v1/users/{userId}/details
// Composed URL - /v1/users/[email protected]/details
//
// client.R().SetPathParam("path", "groups/developers")
//
// Result:
// URL - /v1/users/{userId}/details
// Composed URL - /v1/users/groups%2Fdevelopers/details
//
// It replaces the value of the key while composing the request URL.
// The values will be escaped using function [url.PathEscape].
//
// It overrides the path parameter set at the client instance level.
func (r *Request) SetPathParam(param, value string) *Request {
r.PathParams[param] = url.PathEscape(value)
return r
}
// SetPathParams method sets multiple URL path key-value pairs at one go in the
// Resty current request instance.
//
// client.R().SetPathParams(map[string]string{
// "userId": "[email protected]",
// "subAccountId": "100002",
// "path": "groups/developers",
// })
//
// Result:
// URL - /v1/users/{userId}/{subAccountId}/{path}/details
// Composed URL - /v1/users/[email protected]/100002/groups%2Fdevelopers/details
//
// It replaces the value of the key while composing the request URL.
// The values will be escaped using function [url.PathEscape].
//
// It overrides the path parameter set at the client instance level.
func (r *Request) SetPathParams(params map[string]string) *Request {
for p, v := range params {
r.SetPathParam(p, v)
}
return r
}
// SetRawPathParam method sets a single URL path key-value pair in the
// Resty current request instance without path escape.
//
// client.R().SetPathParam("userId", "[email protected]")
//
// Result:
// URL - /v1/users/{userId}/details
// Composed URL - /v1/users/[email protected]/details
//
// client.R().SetPathParam("path", "groups/developers")
//
// Result:
// URL - /v1/users/{userId}/details
// Composed URL - /v1/users/groups/developers/details
//
// It replaces the value of the key while composing the request URL.
// The value will be used as-is, no path escape applied.
//
// It overrides the raw path parameter set at the client instance level.
func (r *Request) SetRawPathParam(param, value string) *Request {
r.PathParams[param] = value
return r
}
// SetRawPathParams method sets multiple URL path key-value pairs at one go in the
// Resty current request instance without path escape.
//
// client.R().SetPathParams(map[string]string{
// "userId": "[email protected]",
// "subAccountId": "100002",
// "path": "groups/developers",
// })
//
// Result:
// URL - /v1/users/{userId}/{subAccountId}/{path}/details
// Composed URL - /v1/users/[email protected]/100002/groups/developers/details
//
// It replaces the value of the key while composing the request URL.
// The value will be used as-is, no path escape applied.
//
// It overrides the raw path parameter set at the client instance level.
func (r *Request) SetRawPathParams(params map[string]string) *Request {
for p, v := range params {
r.SetRawPathParam(p, v)
}
return r
}
// SetExpectResponseContentType method allows to provide fallback `Content-Type`
// for automatic unmarshalling when the `Content-Type` response header is unavailable.
func (r *Request) SetExpectResponseContentType(contentType string) *Request {
r.ExpectResponseContentType = contentType
return r
}
// SetForceResponseContentType method provides a strong sense of response `Content-Type` for
// automatic unmarshalling. Resty gives this a higher priority than the `Content-Type`
// response header.
//
// This means that if both [Request.SetForceResponseContentType] is set and
// the response `Content-Type` is available, `SetForceResponseContentType` value will win.
func (r *Request) SetForceResponseContentType(contentType string) *Request {
r.ForceResponseContentType = contentType
return r
}
// SetJSONEscapeHTML method enables or disables the HTML escape on JSON marshal.
// By default, escape HTML is `true`.
//
// NOTE: This option only applies to the standard JSON Marshaller used by Resty.
//
// It overrides the value set at the client instance level, see [Client.SetJSONEscapeHTML]
func (r *Request) SetJSONEscapeHTML(b bool) *Request {
r.jsonEscapeHTML = b
return r
}
// SetCookie method appends a single cookie in the current request instance.
//
// client.R().SetCookie(&http.Cookie{
// Name:"go-resty",
// Value:"This is cookie value",
// })
//
// NOTE: Method appends the Cookie value into existing Cookie even if its already existing.
func (r *Request) SetCookie(hc *http.Cookie) *Request {
r.Cookies = append(r.Cookies, hc)
return r
}
// SetCookies method sets an array of cookies in the current request 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's current request
// client.R().SetCookies(cookies)
//
// NOTE: Method appends the Cookie value into existing Cookie even if its already existing.
func (r *Request) SetCookies(rs []*http.Cookie) *Request {
r.Cookies = append(r.Cookies, rs...)
return r
}
// SetTimeout method is used to set a timeout for the current request
//
// client.R().SetTimeout(1 * time.Minute)
//
// It overrides the timeout set at the client instance level, See [Client.SetTimeout]
//
// NOTE: Resty uses [context.WithTimeout] on the request, it does not use [http.Client.Timeout]
func (r *Request) SetTimeout(timeout time.Duration) *Request {
r.Timeout = timeout
return r
}
// SetLogger method sets given writer for logging Resty request and response details.
// By default, requests and responses inherit their logger from the client.
//
// Compliant to interface [resty.Logger].
//
// It overrides the logger value set at the client instance level.
func (r *Request) SetLogger(l Logger) *Request {
r.log = l
return r
}
// EnableDebug method is a helper method for [Request.SetDebug]
func (r *Request) EnableDebug() *Request {
r.SetDebug(true)
return r
}
// DisableDebug method is a helper method for [Request.SetDebug]
func (r *Request) DisableDebug() *Request {
r.SetDebug(false)
return r
}
// SetDebug method enables the debug mode on the current request. It logs
// the details current request and response.
//
// client.R().SetDebug(true)
// // OR
// client.R().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 (r *Request) SetDebug(d bool) *Request {
r.Debug = d
return r
}
// AddRetryConditions method adds one or more retry condition functions into the request.
// These retry conditions are executed to determine if the request can be retried.
// The request will retry if any functions return `true`, otherwise return `false`.
//
// NOTE:
// - The default retry conditions are applied first.
// - The client-level retry conditions are applied to all requests.
// - The request-level retry conditions are executed first before the client-level
// retry conditions. See [Request.SetRetryConditions]
func (r *Request) AddRetryConditions(conditions ...RetryConditionFunc) *Request {
r.retryConditions = append(r.retryConditions, conditions...)
return r
}
// SetRetryConditions method overwrites the retry conditions in the request.
// These retry conditions are executed to determine if the request can be retried.
// The request will retry if any function returns `true`, otherwise return `false`.
func (r *Request) SetRetryConditions(conditions ...RetryConditionFunc) *Request {
r.retryConditions = conditions
return r
}
// AddRetryHooks method adds one or more side-effecting retry hooks in the request.
//
// NOTE:
// - All the retry hooks are executed on each request retry.
// - The request-level retry hooks are executed first before the client-level hooks.
func (r *Request) AddRetryHooks(hooks ...RetryHookFunc) *Request {
r.retryHooks = append(r.retryHooks, hooks...)
return r
}