forked from gofiber/fiber
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.go
More file actions
1122 lines (960 loc) · 27.8 KB
/
Copy pathrequest.go
File metadata and controls
1122 lines (960 loc) · 27.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
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 client
import (
"bytes"
"context"
"errors"
"io"
"iter"
"maps"
"path/filepath"
"reflect"
"slices"
"sort"
"strconv"
"sync"
"time"
"github.com/gofiber/fiber/v3"
utils "github.com/gofiber/utils/v2"
"github.com/valyala/fasthttp"
)
// WithStruct is implemented by types that allow data to be stored from a struct via reflection.
type WithStruct interface {
Add(name, obj string)
Del(name string)
}
// bodyType defines the type of request body.
type bodyType int
// Enumeration of request body types.
const (
noBody bodyType = iota
jsonBody
xmlBody
formBody
filesBody
rawBody
cborBody
)
var ErrClientNil = errors.New("client cannot be nil")
// Request contains all data related to an HTTP request.
type Request struct {
ctx context.Context //nolint:containedctx // Context is needed to be stored in the request.
body any
header Header
params QueryParam
cookies Cookie
path PathParam
client *Client
formData FormData
RawRequest *fasthttp.Request
url string
method string
userAgent string
boundary string
referer string
files []*File
timeout time.Duration
maxRedirects int
bodyType bodyType
disablePathNormalizing bool
}
// Method returns the HTTP method set in the Request.
func (r *Request) Method() string {
return r.method
}
// SetMethod sets the HTTP method for the Request.
// It is recommended to use the specialized methods (e.g., Get, Post) instead.
func (r *Request) SetMethod(method string) *Request {
r.method = method
return r
}
// URL returns the URL set in the Request.
func (r *Request) URL() string {
return r.url
}
// SetURL sets the URL for the Request.
func (r *Request) SetURL(url string) *Request {
r.url = url
return r
}
// Client returns the Client instance associated with this Request.
func (r *Request) Client() *Client {
return r.client
}
// SetClient sets the Client instance for the Request.
func (r *Request) SetClient(c *Client) *Request {
if c == nil {
panic(ErrClientNil)
}
r.client = c
return r
}
// Context returns the context associated with the Request.
// If not set, a background context is returned.
func (r *Request) Context() context.Context {
if r.ctx == nil {
return context.Background()
}
return r.ctx
}
// SetContext sets the context for the Request, allowing request cancellation if ctx is done.
// See https://blog.golang.org/context article and the "context" package documentation.
func (r *Request) SetContext(ctx context.Context) *Request {
r.ctx = ctx
return r
}
// Header returns all values associated with the given header key.
func (r *Request) Header(key string) []string {
return r.header.PeekMultiple(key)
}
type pair struct {
k []string
v []string
}
// Len implements sort.Interface and reports the number of tracked keys.
func (p *pair) Len() int {
return len(p.k)
}
// Swap implements sort.Interface and swaps the entries at the provided indices.
func (p *pair) Swap(i, j int) {
p.k[i], p.k[j] = p.k[j], p.k[i]
p.v[i], p.v[j] = p.v[j], p.v[i]
}
// Less implements sort.Interface and orders entries lexicographically by key.
func (p *pair) Less(i, j int) bool {
return p.k[i] < p.k[j]
}
// Headers returns an iterator over all headers in the Request.
// Use maps.Collect() to gather them into a map if needed.
//
// The returned values are only valid until the request object is released.
// Do not store references to returned values; make copies instead.
func (r *Request) Headers() iter.Seq2[string, []string] {
return func(yield func(string, []string) bool) {
peekKeys := r.header.PeekKeys()
// Copy keys to immutable strings to decouple from fasthttp's internal buffers.
keys := make([]string, len(peekKeys))
for i, key := range peekKeys {
keys[i] = utils.UnsafeString(key)
}
for _, key := range keys {
vals := r.header.PeekAll(key)
valsStr := make([]string, len(vals))
for i, v := range vals {
valsStr[i] = utils.UnsafeString(v)
}
if !yield(key, valsStr) {
return
}
}
}
}
// AddHeader adds a single header field and value to the Request.
func (r *Request) AddHeader(key, val string) *Request {
r.header.Add(key, val)
return r
}
// SetHeader sets a single header field and value in the Request, overriding any previously set value.
func (r *Request) SetHeader(key, val string) *Request {
r.header.Del(key)
r.header.Set(key, val)
return r
}
// AddHeaders adds multiple header fields and values at once.
func (r *Request) AddHeaders(h map[string][]string) *Request {
r.header.AddHeaders(h)
return r
}
// SetHeaders sets multiple header fields and values at once, overriding previously set values.
func (r *Request) SetHeaders(h map[string]string) *Request {
r.header.SetHeaders(h)
return r
}
// Param returns all values associated with the given query parameter.
func (r *Request) Param(key string) []string {
tmp := r.params.PeekMulti(key)
res := make([]string, 0, len(tmp))
for _, v := range tmp {
res = append(res, utils.UnsafeString(v))
}
return res
}
// Params returns an iterator over all query parameters in the Request.
// Use maps.Collect() to gather them into a map if needed.
//
// The returned values are only valid until the request object is released.
// Do not store references to returned values; make copies instead.
func (r *Request) Params() iter.Seq2[string, []string] {
return func(yield func(string, []string) bool) {
vals := r.params.Len()
if vals == 0 {
return
}
prealloc := make([]string, 2*vals)
p := pair{
k: prealloc[:0:vals],
v: prealloc[vals : vals : 2*vals],
}
for k, v := range r.params.All() {
p.k = append(p.k, utils.UnsafeString(k))
p.v = append(p.v, utils.UnsafeString(v))
}
sort.Sort(&p)
j := 0
for i := range vals {
if i == vals-1 || p.k[i] != p.k[i+1] {
if !yield(p.k[i], p.v[j:i+1]) {
break
}
j = i + 1
}
}
}
}
// AddParam adds a single query parameter and value to the Request.
func (r *Request) AddParam(key, val string) *Request {
r.params.Add(key, val)
return r
}
// SetParam sets a single query parameter and value in the Request, overriding any previously set value.
func (r *Request) SetParam(key, val string) *Request {
r.params.Set(key, val)
return r
}
// AddParams adds multiple query parameters and their values at once.
func (r *Request) AddParams(m map[string][]string) *Request {
r.params.AddParams(m)
return r
}
// SetParams sets multiple query parameters and their values at once, overriding previously set values.
func (r *Request) SetParams(m map[string]string) *Request {
r.params.SetParams(m)
return r
}
// SetParamsWithStruct sets multiple query parameters from a struct, overriding previously set values.
func (r *Request) SetParamsWithStruct(v any) *Request {
r.params.SetParamsWithStruct(v)
return r
}
// DelParams deletes one or more query parameters.
func (r *Request) DelParams(key ...string) *Request {
for _, v := range key {
r.params.Del(v)
}
return r
}
// UserAgent returns the User-Agent header set in the Request.
func (r *Request) UserAgent() string {
return r.userAgent
}
// SetUserAgent sets the User-Agent header, overriding any previously set value.
func (r *Request) SetUserAgent(ua string) *Request {
r.userAgent = ua
return r
}
// Boundary returns the multipart boundary used by the Request.
func (r *Request) Boundary() string {
return r.boundary
}
// SetBoundary sets the multipart boundary.
func (r *Request) SetBoundary(b string) *Request {
r.boundary = b
return r
}
// Referer returns the Referer header set in the Request.
func (r *Request) Referer() string {
return r.referer
}
// SetReferer sets the Referer header, overriding any previously set value.
func (r *Request) SetReferer(referer string) *Request {
r.referer = referer
return r
}
// Cookie returns the value of a named cookie.
// If the cookie does not exist, an empty string is returned.
func (r *Request) Cookie(key string) string {
if val, ok := (r.cookies)[key]; ok {
return val
}
return ""
}
// Cookies returns an iterator over all cookies.
// Use maps.Collect() to gather them into a map if needed.
func (r *Request) Cookies() iter.Seq2[string, string] {
return r.cookies.All()
}
// SetCookie sets a single cookie, overriding any previously set value.
func (r *Request) SetCookie(key, val string) *Request {
r.cookies.SetCookie(key, val)
return r
}
// SetCookies sets multiple cookies at once, overriding previously set values.
func (r *Request) SetCookies(m map[string]string) *Request {
r.cookies.SetCookies(m)
return r
}
// SetCookiesWithStruct sets multiple cookies from a struct, overriding previously set values.
func (r *Request) SetCookiesWithStruct(v any) *Request {
r.cookies.SetCookiesWithStruct(v)
return r
}
// DelCookies deletes one or more cookies.
func (r *Request) DelCookies(key ...string) *Request {
r.cookies.DelCookies(key...)
return r
}
// PathParam returns the value of a named path parameter.
// If the parameter does not exist, an empty string is returned.
func (r *Request) PathParam(key string) string {
if val, ok := (r.path)[key]; ok {
return val
}
return ""
}
// PathParams returns an iterator over all path parameters.
// Use maps.Collect() to gather them into a map if needed.
func (r *Request) PathParams() iter.Seq2[string, string] {
return r.path.All()
}
// SetPathParam sets a single path parameter and value, overriding any previously set value.
func (r *Request) SetPathParam(key, val string) *Request {
r.path.SetParam(key, val)
return r
}
// SetPathParams sets multiple path parameters and values at once, overriding previously set values.
func (r *Request) SetPathParams(m map[string]string) *Request {
r.path.SetParams(m)
return r
}
// SetPathParamsWithStruct sets multiple path parameters from a struct, overriding previously set values.
func (r *Request) SetPathParamsWithStruct(v any) *Request {
r.path.SetParamsWithStruct(v)
return r
}
// DelPathParams deletes one or more path parameters.
func (r *Request) DelPathParams(key ...string) *Request {
r.path.DelParams(key...)
return r
}
// ResetPathParams deletes all path parameters.
func (r *Request) ResetPathParams() *Request {
r.path.Reset()
return r
}
// SetJSON sets the request body to a JSON-encoded value.
func (r *Request) SetJSON(v any) *Request {
r.body = v
r.bodyType = jsonBody
return r
}
// SetXML sets the request body to an XML-encoded value.
func (r *Request) SetXML(v any) *Request {
r.body = v
r.bodyType = xmlBody
return r
}
// SetCBOR sets the request body to a CBOR-encoded value.
func (r *Request) SetCBOR(v any) *Request {
r.body = v
r.bodyType = cborBody
return r
}
// SetRawBody sets the request body to raw bytes.
func (r *Request) SetRawBody(v []byte) *Request {
r.body = v
r.bodyType = rawBody
return r
}
// resetBody clears the existing body. If the current body type is filesBody and
// the new type is formBody, the formBody setting is ignored to preserve files.
func (r *Request) resetBody(t bodyType) {
r.body = nil
// If bodyType is filesBody and we attempt to set formBody, ignore the change.
if r.bodyType == filesBody && t == formBody {
return
}
r.bodyType = t
}
// FormData returns all values associated with a form field.
func (r *Request) FormData(key string) []string {
tmp := r.formData.PeekMulti(key)
res := make([]string, 0, len(tmp))
for _, v := range tmp {
res = append(res, utils.UnsafeString(v))
}
return res
}
// AllFormData returns an iterator over all form fields.
// Use maps.Collect() to gather them into a map if needed.
//
// The returned values are only valid until the request object is released.
// Do not store references to returned values; make copies instead.
func (r *Request) AllFormData() iter.Seq2[string, []string] {
return func(yield func(string, []string) bool) {
vals := r.formData.Len()
if vals == 0 {
return
}
prealloc := make([]string, 2*vals)
p := pair{
k: prealloc[:0:vals],
v: prealloc[vals : vals : 2*vals],
}
for k, v := range r.formData.All() {
p.k = append(p.k, utils.UnsafeString(k))
p.v = append(p.v, utils.UnsafeString(v))
}
sort.Sort(&p)
j := 0
for i := range vals {
if i == vals-1 || p.k[i] != p.k[i+1] {
if !yield(p.k[i], p.v[j:i+1]) {
break
}
j = i + 1
}
}
}
}
// AddFormData adds a single form field and value to the Request.
func (r *Request) AddFormData(key, val string) *Request {
r.formData.Add(key, val)
r.resetBody(formBody)
return r
}
// SetFormData sets a single form field and value, overriding any previously set value.
func (r *Request) SetFormData(key, val string) *Request {
r.formData.Set(key, val)
r.resetBody(formBody)
return r
}
// AddFormDataWithMap adds multiple form fields and values to the Request.
func (r *Request) AddFormDataWithMap(m map[string][]string) *Request {
r.formData.AddWithMap(m)
r.resetBody(formBody)
return r
}
// SetFormDataWithMap sets multiple form fields and values at once, overriding previously set values.
func (r *Request) SetFormDataWithMap(m map[string]string) *Request {
r.formData.SetWithMap(m)
r.resetBody(formBody)
return r
}
// SetFormDataWithStruct sets multiple form fields from a struct, overriding previously set values.
func (r *Request) SetFormDataWithStruct(v any) *Request {
r.formData.SetWithStruct(v)
r.resetBody(formBody)
return r
}
// DelFormData deletes one or more form fields.
func (r *Request) DelFormData(key ...string) *Request {
r.formData.DelData(key...)
r.resetBody(formBody)
return r
}
// File returns the file associated with the given name.
// If no name was provided during addition, it attempts to match by the file's base name.
func (r *Request) File(name string) *File {
for _, v := range r.files {
switch v.name {
case "":
if filepath.Base(v.path) == name {
return v
}
case name:
return v
default:
continue
}
}
return nil
}
// Files returns all files added to the Request.
//
// The returned values are only valid until the request object is released.
// Do not store references to returned values; make copies instead.
func (r *Request) Files() []*File {
return r.files
}
// FileByPath returns the file associated with the given file path.
func (r *Request) FileByPath(path string) *File {
for _, v := range r.files {
if v.path == path {
return v
}
}
return nil
}
// AddFile adds a single file by its path.
func (r *Request) AddFile(path string) *Request {
r.files = append(r.files, AcquireFile(SetFilePath(path)))
r.resetBody(filesBody)
return r
}
// AddFileWithReader adds a file using an io.ReadCloser.
func (r *Request) AddFileWithReader(name string, reader io.ReadCloser) *Request {
r.files = append(r.files, AcquireFile(SetFileName(name), SetFileReader(reader)))
r.resetBody(filesBody)
return r
}
// AddFiles adds multiple files at once.
func (r *Request) AddFiles(files ...*File) *Request {
r.files = append(r.files, files...)
r.resetBody(filesBody)
return r
}
// Timeout returns the timeout duration set in the Request.
func (r *Request) Timeout() time.Duration {
return r.timeout
}
// SetTimeout sets the timeout for the Request, overriding any previously set value.
func (r *Request) SetTimeout(t time.Duration) *Request {
r.timeout = t
return r
}
// MaxRedirects returns the maximum number of redirects configured for the Request.
func (r *Request) MaxRedirects() int {
return r.maxRedirects
}
// SetMaxRedirects sets the maximum number of redirects, overriding any previously set value.
func (r *Request) SetMaxRedirects(count int) *Request {
r.maxRedirects = count
return r
}
// DisablePathNormalizing reports whether path normalizing is disabled for the Request.
func (r *Request) DisablePathNormalizing() bool {
return r.disablePathNormalizing
}
// SetDisablePathNormalizing configures the Request to disable or enable path normalizing.
func (r *Request) SetDisablePathNormalizing(disable bool) *Request {
r.disablePathNormalizing = disable
r.RawRequest.URI().DisablePathNormalizing = disable
return r
}
// checkClient ensures that a Client is set. If none is set, it defaults to the global defaultClient.
func (r *Request) checkClient() {
if r.client == nil {
r.SetClient(defaultClient)
}
}
// Get sends a GET request to the given URL.
func (r *Request) Get(url string) (*Response, error) {
return r.SetURL(url).SetMethod(fiber.MethodGet).Send()
}
// Post sends a POST request to the given URL.
func (r *Request) Post(url string) (*Response, error) {
return r.SetURL(url).SetMethod(fiber.MethodPost).Send()
}
// Head sends a HEAD request to the given URL.
func (r *Request) Head(url string) (*Response, error) {
return r.SetURL(url).SetMethod(fiber.MethodHead).Send()
}
// Put sends a PUT request to the given URL.
func (r *Request) Put(url string) (*Response, error) {
return r.SetURL(url).SetMethod(fiber.MethodPut).Send()
}
// Delete sends a DELETE request to the given URL.
func (r *Request) Delete(url string) (*Response, error) {
return r.SetURL(url).SetMethod(fiber.MethodDelete).Send()
}
// Options sends an OPTIONS request to the given URL.
func (r *Request) Options(url string) (*Response, error) {
return r.SetURL(url).SetMethod(fiber.MethodOptions).Send()
}
// Patch sends a PATCH request to the given URL.
func (r *Request) Patch(url string) (*Response, error) {
return r.SetURL(url).SetMethod(fiber.MethodPatch).Send()
}
// Custom sends a request with a custom HTTP method to the given URL.
func (r *Request) Custom(url, method string) (*Response, error) {
return r.SetURL(url).SetMethod(method).Send()
}
// Send executes the Request.
func (r *Request) Send() (*Response, error) {
r.checkClient()
return newCore().execute(r.Context(), r.Client(), r)
}
// Reset clears the Request object, returning it to its default state.
// Used by ReleaseRequest to recycle the object.
func (r *Request) Reset() {
r.url = ""
r.method = fiber.MethodGet
r.userAgent = ""
r.referer = ""
r.ctx = nil
r.body = nil
r.timeout = 0
r.maxRedirects = 0
r.bodyType = noBody
r.boundary = boundary
r.disablePathNormalizing = false
for len(r.files) != 0 {
t := r.files[0]
r.files = r.files[1:]
ReleaseFile(t)
}
r.formData.Reset()
r.path.Reset()
r.cookies.Reset()
r.header.Reset()
r.params.Reset()
r.RawRequest.Reset()
}
// Header wraps fasthttp.RequestHeader, storing headers for both client and request.
type Header struct {
*fasthttp.RequestHeader
}
// PeekMultiple returns multiple values of a header field with the same key.
func (h *Header) PeekMultiple(key string) []string {
var res []string
byteKey := []byte(key)
for k, value := range h.All() {
if bytes.EqualFold(k, byteKey) {
res = append(res, utils.UnsafeString(value))
}
}
return res
}
// AddHeaders adds multiple headers from a map.
func (h *Header) AddHeaders(r map[string][]string) {
for k, v := range r {
for _, vv := range v {
h.Add(k, vv)
}
}
}
// SetHeaders sets multiple headers from a map, overriding previously set values.
func (h *Header) SetHeaders(r map[string]string) {
for k, v := range r {
h.Del(k)
h.Set(k, v)
}
}
// QueryParam wraps fasthttp.Args for query parameters.
type QueryParam struct {
*fasthttp.Args
}
// Keys returns all keys from the query parameters.
func (p *QueryParam) Keys() []string {
keys := make([]string, 0, p.Len())
for key := range p.All() {
keys = append(keys, utils.UnsafeString(key))
}
return slices.Compact(keys)
}
// AddParams adds multiple parameters from a map.
func (p *QueryParam) AddParams(r map[string][]string) {
for k, v := range r {
for _, vv := range v {
p.Add(k, vv)
}
}
}
// SetParams sets multiple parameters from a map, overriding previously set values.
func (p *QueryParam) SetParams(r map[string]string) {
for k, v := range r {
p.Set(k, v)
}
}
// SetParamsWithStruct sets multiple parameters from a struct.
// Nested structs are not currently supported.
func (p *QueryParam) SetParamsWithStruct(v any) {
SetValWithStruct(p, "param", v)
}
// Cookie is a map used to store cookies.
type Cookie map[string]string
// Add adds a cookie key-value pair.
func (c Cookie) Add(key, val string) {
c[key] = val
}
// Del deletes a cookie by key.
func (c Cookie) Del(key string) {
delete(c, key)
}
// SetCookie sets a single cookie value.
func (c Cookie) SetCookie(key, val string) {
c[key] = val
}
// SetCookies sets multiple cookies from a map.
func (c Cookie) SetCookies(m map[string]string) {
maps.Copy(c, m)
}
// SetCookiesWithStruct sets cookies from a struct.
// Nested structs are not currently supported.
func (c Cookie) SetCookiesWithStruct(v any) {
SetValWithStruct(c, "cookie", v)
}
// DelCookies deletes multiple cookies by keys.
func (c Cookie) DelCookies(key ...string) {
for _, v := range key {
c.Del(v)
}
}
// All returns an iterator over cookie key-value pairs.
//
// The returned key and value should not be retained after the iteration loop.
func (c Cookie) All() iter.Seq2[string, string] {
return maps.All(c)
}
// Reset clears the Cookie map.
func (c Cookie) Reset() {
clear(c)
}
// PathParam is a map used to store path parameters.
type PathParam map[string]string
// Add adds a path parameter key-value pair.
func (p PathParam) Add(key, val string) {
p[key] = val
}
// Del deletes a path parameter by key.
func (p PathParam) Del(key string) {
delete(p, key)
}
// SetParam sets a single path parameter.
func (p PathParam) SetParam(key, val string) {
p[key] = val
}
// SetParams sets multiple path parameters from a map.
func (p PathParam) SetParams(m map[string]string) {
maps.Copy(p, m)
}
// SetParamsWithStruct sets multiple path parameters from a struct.
// Nested structs are not currently supported.
func (p PathParam) SetParamsWithStruct(v any) {
SetValWithStruct(p, "path", v)
}
// DelParams deletes multiple path parameters.
func (p PathParam) DelParams(key ...string) {
for _, v := range key {
p.Del(v)
}
}
// All returns an iterator over path parameter key-value pairs.
//
// The returned key and value should not be retained after the iteration loop.
func (p PathParam) All() iter.Seq2[string, string] {
return maps.All(p)
}
// Reset clears the PathParam map.
func (p PathParam) Reset() {
clear(p)
}
// FormData wraps fasthttp.Args for URL-encoded bodies and form data.
type FormData struct {
*fasthttp.Args
}
// Keys returns all keys from the form data.
func (f *FormData) Keys() []string {
keys := make([]string, 0, f.Len())
for key := range f.All() {
keys = append(keys, utils.UnsafeString(key))
}
return slices.Compact(keys)
}
// Add adds a single form field.
func (f *FormData) Add(key, val string) {
f.Args.Add(key, val)
}
// Set sets a single form field, overriding previously set values.
func (f *FormData) Set(key, val string) {
f.Args.Set(key, val)
}
// AddWithMap adds multiple form fields from a map.
func (f *FormData) AddWithMap(m map[string][]string) {
for k, v := range m {
for _, vv := range v {
f.Add(k, vv)
}
}
}
// SetWithMap sets multiple form fields from a map, overriding previously set values.
func (f *FormData) SetWithMap(m map[string]string) {
for k, v := range m {
f.Set(k, v)
}
}
// SetWithStruct sets multiple form fields from a struct.
// Nested structs are not currently supported.
func (f *FormData) SetWithStruct(v any) {
SetValWithStruct(f, "form", v)
}
// DelData deletes multiple form fields.
func (f *FormData) DelData(key ...string) {
for _, v := range key {
f.Del(v)
}
}
// Reset clears the FormData object.
func (f *FormData) Reset() {
f.Args.Reset()
}
// File represents a file to be sent with the request.
type File struct {
reader io.ReadCloser
name string
fieldName string
path string
}
// SetName sets the file's name.
func (f *File) SetName(n string) {
f.name = n
}
// SetFieldName sets the key associated with the file in the body.
func (f *File) SetFieldName(n string) {
f.fieldName = n
}
// SetPath sets the file's path.
func (f *File) SetPath(p string) {
f.path = p
}
// SetReader sets the file's reader, which will be closed in the parserBody hook.
func (f *File) SetReader(r io.ReadCloser) {
f.reader = r
}
// Reset clears the File object.
func (f *File) Reset() {
f.name = ""
f.fieldName = ""
f.path = ""
f.reader = nil
}
var requestPool = &sync.Pool{
New: func() any {
return &Request{
header: Header{RequestHeader: &fasthttp.RequestHeader{}},
params: QueryParam{Args: fasthttp.AcquireArgs()},
cookies: Cookie{},
path: PathParam{},
boundary: boundary,
formData: FormData{Args: fasthttp.AcquireArgs()},
files: make([]*File, 0),
RawRequest: fasthttp.AcquireRequest(),
}
},
}
// AcquireRequest returns a new (pooled) Request object.
func AcquireRequest() *Request {
req, ok := requestPool.Get().(*Request)
if !ok {
panic(errors.New("failed to type-assert to *Request"))
}
return req
}
// ReleaseRequest returns the Request object to the pool.
// Do not use the released Request afterward to avoid data races.
func ReleaseRequest(req *Request) {
req.Reset()
requestPool.Put(req)
}
var filePool sync.Pool
// SetFileFunc defines a function that modifies a File object.