forked from gofiber/fiber
-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
1017 lines (827 loc) · 24.7 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package fiber
import (
"bytes"
"crypto/tls"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"mime/multipart"
"os"
"path/filepath"
"strconv"
"sync"
"time"
"github.com/gofiber/fiber/v2/utils"
"github.com/valyala/fasthttp"
)
// Request represents HTTP request.
//
// It is forbidden copying Request instances. Create new instances
// and use CopyTo instead.
//
// Request instance MUST NOT be used from concurrently running goroutines.
// Copy from fasthttp
type Request = fasthttp.Request
// Response represents HTTP response.
//
// It is forbidden copying Response instances. Create new instances
// and use CopyTo instead.
//
// Response instance MUST NOT be used from concurrently running goroutines.
// Copy from fasthttp
type Response = fasthttp.Response
// Args represents query arguments.
//
// It is forbidden copying Args instances. Create new instances instead
// and use CopyTo().
//
// Args instance MUST NOT be used from concurrently running goroutines.
// Copy from fasthttp
type Args = fasthttp.Args
// RetryIfFunc signature of retry if function
// Request argument passed to RetryIfFunc, if there are any request errors.
// Copy from fasthttp
type RetryIfFunc = fasthttp.RetryIfFunc
var defaultClient Client
// Client implements http client.
//
// It is safe calling Client methods from concurrently running goroutines.
type Client struct {
mutex sync.RWMutex
// UserAgent is used in User-Agent request header.
UserAgent string
// NoDefaultUserAgentHeader when set to true, causes the default
// User-Agent header to be excluded from the Request.
NoDefaultUserAgentHeader bool
// When set by an external client of Fiber it will use the provided implementation of a
// JSONMarshal
//
// Allowing for flexibility in using another json library for encoding
JSONEncoder utils.JSONMarshal
// When set by an external client of Fiber it will use the provided implementation of a
// JSONUnmarshal
//
// Allowing for flexibility in using another json library for decoding
JSONDecoder utils.JSONUnmarshal
}
// Get returns a agent with http method GET.
func Get(url string) *Agent { return defaultClient.Get(url) }
// Get returns a agent with http method GET.
func (c *Client) Get(url string) *Agent {
return c.createAgent(MethodGet, url)
}
// Head returns a agent with http method HEAD.
func Head(url string) *Agent { return defaultClient.Head(url) }
// Head returns a agent with http method GET.
func (c *Client) Head(url string) *Agent {
return c.createAgent(MethodHead, url)
}
// Post sends POST request to the given url.
func Post(url string) *Agent { return defaultClient.Post(url) }
// Post sends POST request to the given url.
func (c *Client) Post(url string) *Agent {
return c.createAgent(MethodPost, url)
}
// Put sends PUT request to the given url.
func Put(url string) *Agent { return defaultClient.Put(url) }
// Put sends PUT request to the given url.
func (c *Client) Put(url string) *Agent {
return c.createAgent(MethodPut, url)
}
// Patch sends PATCH request to the given url.
func Patch(url string) *Agent { return defaultClient.Patch(url) }
// Patch sends PATCH request to the given url.
func (c *Client) Patch(url string) *Agent {
return c.createAgent(MethodPatch, url)
}
// Delete sends DELETE request to the given url.
func Delete(url string) *Agent { return defaultClient.Delete(url) }
// Delete sends DELETE request to the given url.
func (c *Client) Delete(url string) *Agent {
return c.createAgent(MethodDelete, url)
}
func (c *Client) createAgent(method, url string) *Agent {
a := AcquireAgent()
a.req.Header.SetMethod(method)
a.req.SetRequestURI(url)
c.mutex.RLock()
a.Name = c.UserAgent
a.NoDefaultUserAgentHeader = c.NoDefaultUserAgentHeader
a.jsonDecoder = c.JSONDecoder
a.jsonEncoder = c.JSONEncoder
if a.jsonDecoder == nil {
a.jsonDecoder = json.Unmarshal
}
c.mutex.RUnlock()
if err := a.Parse(); err != nil {
a.errs = append(a.errs, err)
}
return a
}
// Agent is an object storing all request data for client.
// Agent instance MUST NOT be used from concurrently running goroutines.
type Agent struct {
// Name is used in User-Agent request header.
Name string
// NoDefaultUserAgentHeader when set to true, causes the default
// User-Agent header to be excluded from the Request.
NoDefaultUserAgentHeader bool
// HostClient is an embedded fasthttp HostClient
*fasthttp.HostClient
req *Request
resp *Response
dest []byte
args *Args
timeout time.Duration
errs []error
formFiles []*FormFile
debugWriter io.Writer
mw multipartWriter
jsonEncoder utils.JSONMarshal
jsonDecoder utils.JSONUnmarshal
maxRedirectsCount int
boundary string
reuse bool
parsed bool
}
// Parse initializes URI and HostClient.
func (a *Agent) Parse() error {
if a.parsed {
return nil
}
a.parsed = true
uri := a.req.URI()
var isTLS bool
scheme := uri.Scheme()
if bytes.Equal(scheme, []byte(schemeHTTPS)) {
isTLS = true
} else if !bytes.Equal(scheme, []byte(schemeHTTP)) {
return fmt.Errorf("unsupported protocol %q. http and https are supported", scheme)
}
name := a.Name
if name == "" && !a.NoDefaultUserAgentHeader {
name = defaultUserAgent
}
a.HostClient = &fasthttp.HostClient{
Addr: fasthttp.AddMissingPort(string(uri.Host()), isTLS),
Name: name,
NoDefaultUserAgentHeader: a.NoDefaultUserAgentHeader,
IsTLS: isTLS,
}
return nil
}
/************************** Header Setting **************************/
// Set sets the given 'key: value' header.
//
// Use Add for setting multiple header values under the same key.
func (a *Agent) Set(k, v string) *Agent {
a.req.Header.Set(k, v)
return a
}
// SetBytesK sets the given 'key: value' header.
//
// Use AddBytesK for setting multiple header values under the same key.
func (a *Agent) SetBytesK(k []byte, v string) *Agent {
a.req.Header.SetBytesK(k, v)
return a
}
// SetBytesV sets the given 'key: value' header.
//
// Use AddBytesV for setting multiple header values under the same key.
func (a *Agent) SetBytesV(k string, v []byte) *Agent {
a.req.Header.SetBytesV(k, v)
return a
}
// SetBytesKV sets the given 'key: value' header.
//
// Use AddBytesKV for setting multiple header values under the same key.
func (a *Agent) SetBytesKV(k, v []byte) *Agent {
a.req.Header.SetBytesKV(k, v)
return a
}
// Add adds the given 'key: value' header.
//
// Multiple headers with the same key may be added with this function.
// Use Set for setting a single header for the given key.
func (a *Agent) Add(k, v string) *Agent {
a.req.Header.Add(k, v)
return a
}
// AddBytesK adds the given 'key: value' header.
//
// Multiple headers with the same key may be added with this function.
// Use SetBytesK for setting a single header for the given key.
func (a *Agent) AddBytesK(k []byte, v string) *Agent {
a.req.Header.AddBytesK(k, v)
return a
}
// AddBytesV adds the given 'key: value' header.
//
// Multiple headers with the same key may be added with this function.
// Use SetBytesV for setting a single header for the given key.
func (a *Agent) AddBytesV(k string, v []byte) *Agent {
a.req.Header.AddBytesV(k, v)
return a
}
// AddBytesKV adds the given 'key: value' header.
//
// Multiple headers with the same key may be added with this function.
// Use SetBytesKV for setting a single header for the given key.
func (a *Agent) AddBytesKV(k, v []byte) *Agent {
a.req.Header.AddBytesKV(k, v)
return a
}
// ConnectionClose sets 'Connection: close' header.
func (a *Agent) ConnectionClose() *Agent {
a.req.Header.SetConnectionClose()
return a
}
// UserAgent sets User-Agent header value.
func (a *Agent) UserAgent(userAgent string) *Agent {
a.req.Header.SetUserAgent(userAgent)
return a
}
// UserAgentBytes sets User-Agent header value.
func (a *Agent) UserAgentBytes(userAgent []byte) *Agent {
a.req.Header.SetUserAgentBytes(userAgent)
return a
}
// Cookie sets one 'key: value' cookie.
func (a *Agent) Cookie(key, value string) *Agent {
a.req.Header.SetCookie(key, value)
return a
}
// CookieBytesK sets one 'key: value' cookie.
func (a *Agent) CookieBytesK(key []byte, value string) *Agent {
a.req.Header.SetCookieBytesK(key, value)
return a
}
// CookieBytesKV sets one 'key: value' cookie.
func (a *Agent) CookieBytesKV(key, value []byte) *Agent {
a.req.Header.SetCookieBytesKV(key, value)
return a
}
// Cookies sets multiple 'key: value' cookies.
func (a *Agent) Cookies(kv ...string) *Agent {
for i := 1; i < len(kv); i += 2 {
a.req.Header.SetCookie(kv[i-1], kv[i])
}
return a
}
// CookiesBytesKV sets multiple 'key: value' cookies.
func (a *Agent) CookiesBytesKV(kv ...[]byte) *Agent {
for i := 1; i < len(kv); i += 2 {
a.req.Header.SetCookieBytesKV(kv[i-1], kv[i])
}
return a
}
// Referer sets Referer header value.
func (a *Agent) Referer(referer string) *Agent {
a.req.Header.SetReferer(referer)
return a
}
// RefererBytes sets Referer header value.
func (a *Agent) RefererBytes(referer []byte) *Agent {
a.req.Header.SetRefererBytes(referer)
return a
}
// ContentType sets Content-Type header value.
func (a *Agent) ContentType(contentType string) *Agent {
a.req.Header.SetContentType(contentType)
return a
}
// ContentTypeBytes sets Content-Type header value.
func (a *Agent) ContentTypeBytes(contentType []byte) *Agent {
a.req.Header.SetContentTypeBytes(contentType)
return a
}
/************************** End Header Setting **************************/
/************************** URI Setting **************************/
// Host sets host for the uri.
func (a *Agent) Host(host string) *Agent {
a.req.URI().SetHost(host)
return a
}
// HostBytes sets host for the URI.
func (a *Agent) HostBytes(host []byte) *Agent {
a.req.URI().SetHostBytes(host)
return a
}
// QueryString sets URI query string.
func (a *Agent) QueryString(queryString string) *Agent {
a.req.URI().SetQueryString(queryString)
return a
}
// QueryStringBytes sets URI query string.
func (a *Agent) QueryStringBytes(queryString []byte) *Agent {
a.req.URI().SetQueryStringBytes(queryString)
return a
}
// BasicAuth sets URI username and password.
func (a *Agent) BasicAuth(username, password string) *Agent {
a.req.URI().SetUsername(username)
a.req.URI().SetPassword(password)
return a
}
// BasicAuthBytes sets URI username and password.
func (a *Agent) BasicAuthBytes(username, password []byte) *Agent {
a.req.URI().SetUsernameBytes(username)
a.req.URI().SetPasswordBytes(password)
return a
}
/************************** End URI Setting **************************/
/************************** Request Setting **************************/
// BodyString sets request body.
func (a *Agent) BodyString(bodyString string) *Agent {
a.req.SetBodyString(bodyString)
return a
}
// Body sets request body.
func (a *Agent) Body(body []byte) *Agent {
a.req.SetBody(body)
return a
}
// BodyStream sets request body stream and, optionally body size.
//
// If bodySize is >= 0, then the bodyStream must provide exactly bodySize bytes
// before returning io.EOF.
//
// If bodySize < 0, then bodyStream is read until io.EOF.
//
// bodyStream.Close() is called after finishing reading all body data
// if it implements io.Closer.
//
// Note that GET and HEAD requests cannot have body.
func (a *Agent) BodyStream(bodyStream io.Reader, bodySize int) *Agent {
a.req.SetBodyStream(bodyStream, bodySize)
return a
}
// JSON sends a JSON request.
func (a *Agent) JSON(v interface{}) *Agent {
if a.jsonEncoder == nil {
a.jsonEncoder = json.Marshal
}
a.req.Header.SetContentType(MIMEApplicationJSON)
if body, err := a.jsonEncoder(v); err != nil {
a.errs = append(a.errs, err)
} else {
a.req.SetBody(body)
}
return a
}
// XML sends an XML request.
func (a *Agent) XML(v interface{}) *Agent {
a.req.Header.SetContentType(MIMEApplicationXML)
if body, err := xml.Marshal(v); err != nil {
a.errs = append(a.errs, err)
} else {
a.req.SetBody(body)
}
return a
}
// Form sends form request with body if args is non-nil.
//
// It is recommended obtaining args via AcquireArgs and release it
// manually in performance-critical code.
func (a *Agent) Form(args *Args) *Agent {
a.req.Header.SetContentType(MIMEApplicationForm)
if args != nil {
a.req.SetBody(args.QueryString())
}
return a
}
// FormFile represents multipart form file
type FormFile struct {
// Fieldname is form file's field name
Fieldname string
// Name is form file's name
Name string
// Content is form file's content
Content []byte
// autoRelease indicates if returns the object
// acquired via AcquireFormFile to the pool.
autoRelease bool
}
// FileData appends files for multipart form request.
//
// It is recommended obtaining formFile via AcquireFormFile and release it
// manually in performance-critical code.
func (a *Agent) FileData(formFiles ...*FormFile) *Agent {
a.formFiles = append(a.formFiles, formFiles...)
return a
}
// SendFile reads file and appends it to multipart form request.
func (a *Agent) SendFile(filename string, fieldname ...string) *Agent {
content, err := os.ReadFile(filepath.Clean(filename))
if err != nil {
a.errs = append(a.errs, err)
return a
}
ff := AcquireFormFile()
if len(fieldname) > 0 && fieldname[0] != "" {
ff.Fieldname = fieldname[0]
} else {
ff.Fieldname = "file" + strconv.Itoa(len(a.formFiles)+1)
}
ff.Name = filepath.Base(filename)
ff.Content = append(ff.Content, content...)
ff.autoRelease = true
a.formFiles = append(a.formFiles, ff)
return a
}
// SendFiles reads files and appends them to multipart form request.
//
// Examples:
//
// SendFile("/path/to/file1", "fieldname1", "/path/to/file2")
func (a *Agent) SendFiles(filenamesAndFieldnames ...string) *Agent {
pairs := len(filenamesAndFieldnames)
if pairs&1 == 1 {
filenamesAndFieldnames = append(filenamesAndFieldnames, "")
}
for i := 0; i < pairs; i += 2 {
a.SendFile(filenamesAndFieldnames[i], filenamesAndFieldnames[i+1])
}
return a
}
// Boundary sets boundary for multipart form request.
func (a *Agent) Boundary(boundary string) *Agent {
a.boundary = boundary
return a
}
// MultipartForm sends multipart form request with k-v and files.
//
// It is recommended obtaining args via AcquireArgs and release it
// manually in performance-critical code.
func (a *Agent) MultipartForm(args *Args) *Agent {
if a.mw == nil {
a.mw = multipart.NewWriter(a.req.BodyWriter())
}
if a.boundary != "" {
if err := a.mw.SetBoundary(a.boundary); err != nil {
a.errs = append(a.errs, err)
return a
}
}
a.req.Header.SetMultipartFormBoundary(a.mw.Boundary())
if args != nil {
args.VisitAll(func(key, value []byte) {
if err := a.mw.WriteField(utils.UnsafeString(key), utils.UnsafeString(value)); err != nil {
a.errs = append(a.errs, err)
}
})
}
for _, ff := range a.formFiles {
w, err := a.mw.CreateFormFile(ff.Fieldname, ff.Name)
if err != nil {
a.errs = append(a.errs, err)
continue
}
if _, err = w.Write(ff.Content); err != nil {
a.errs = append(a.errs, err)
}
}
if err := a.mw.Close(); err != nil {
a.errs = append(a.errs, err)
}
return a
}
/************************** End Request Setting **************************/
/************************** Agent Setting **************************/
// Debug mode enables logging request and response detail
func (a *Agent) Debug(w ...io.Writer) *Agent {
a.debugWriter = os.Stdout
if len(w) > 0 {
a.debugWriter = w[0]
}
return a
}
// Timeout sets request timeout duration.
func (a *Agent) Timeout(timeout time.Duration) *Agent {
a.timeout = timeout
return a
}
// Reuse enables the Agent instance to be used again after one request.
//
// If agent is reusable, then it should be released manually when it is no
// longer used.
func (a *Agent) Reuse() *Agent {
a.reuse = true
return a
}
// InsecureSkipVerify controls whether the Agent verifies the server
// certificate chain and host name.
func (a *Agent) InsecureSkipVerify() *Agent {
if a.HostClient.TLSConfig == nil {
a.HostClient.TLSConfig = &tls.Config{InsecureSkipVerify: true} //nolint:gosec // We explicitly let the user set insecure mode here
} else {
a.HostClient.TLSConfig.InsecureSkipVerify = true
}
return a
}
// TLSConfig sets tls config.
func (a *Agent) TLSConfig(config *tls.Config) *Agent {
a.HostClient.TLSConfig = config
return a
}
// MaxRedirectsCount sets max redirect count for GET and HEAD.
func (a *Agent) MaxRedirectsCount(count int) *Agent {
a.maxRedirectsCount = count
return a
}
// JSONEncoder sets custom json encoder.
func (a *Agent) JSONEncoder(jsonEncoder utils.JSONMarshal) *Agent {
a.jsonEncoder = jsonEncoder
return a
}
// JSONDecoder sets custom json decoder.
func (a *Agent) JSONDecoder(jsonDecoder utils.JSONUnmarshal) *Agent {
a.jsonDecoder = jsonDecoder
return a
}
// Request returns Agent request instance.
func (a *Agent) Request() *Request {
return a.req
}
// SetResponse sets custom response for the Agent instance.
//
// It is recommended obtaining custom response via AcquireResponse and release it
// manually in performance-critical code.
func (a *Agent) SetResponse(customResp *Response) *Agent {
a.resp = customResp
return a
}
// Dest sets custom dest.
//
// The contents of dest will be replaced by the response body, if the dest
// is too small a new slice will be allocated.
func (a *Agent) Dest(dest []byte) *Agent {
a.dest = dest
return a
}
// RetryIf controls whether a retry should be attempted after an error.
//
// By default, will use isIdempotent function from fasthttp
func (a *Agent) RetryIf(retryIf RetryIfFunc) *Agent {
a.HostClient.RetryIf = retryIf
return a
}
/************************** End Agent Setting **************************/
// Bytes returns the status code, bytes body and errors of url.
//
// it's not safe to use Agent after calling [Agent.Bytes]
func (a *Agent) Bytes() (int, []byte, []error) {
defer a.release()
return a.bytes()
}
func (a *Agent) bytes() (code int, body []byte, errs []error) { //nolint:nonamedreturns,revive // We want to overwrite the body in a deferred func. TODO: Check if we really need to do this. We eventually want to get rid of all named returns.
if errs = append(errs, a.errs...); len(errs) > 0 {
return code, body, errs
}
var (
req = a.req
resp *Response
nilResp bool
)
if a.resp == nil {
resp = AcquireResponse()
nilResp = true
} else {
resp = a.resp
}
defer func() {
if a.debugWriter != nil {
printDebugInfo(req, resp, a.debugWriter)
}
if len(errs) == 0 {
code = resp.StatusCode()
}
body = append(a.dest, resp.Body()...) //nolint:gocritic // We want to append to the returned slice here
if nilResp {
ReleaseResponse(resp)
}
}()
if a.timeout > 0 {
if err := a.HostClient.DoTimeout(req, resp, a.timeout); err != nil {
errs = append(errs, err)
return code, body, errs
}
} else if a.maxRedirectsCount > 0 && (string(req.Header.Method()) == MethodGet || string(req.Header.Method()) == MethodHead) {
if err := a.HostClient.DoRedirects(req, resp, a.maxRedirectsCount); err != nil {
errs = append(errs, err)
return code, body, errs
}
} else if err := a.HostClient.Do(req, resp); err != nil {
errs = append(errs, err)
}
return code, body, errs
}
func printDebugInfo(req *Request, resp *Response, w io.Writer) {
msg := fmt.Sprintf("Connected to %s(%s)\r\n\r\n", req.URI().Host(), resp.RemoteAddr())
_, _ = w.Write(utils.UnsafeBytes(msg)) //nolint:errcheck // This will never fail
_, _ = req.WriteTo(w) //nolint:errcheck // This will never fail
_, _ = resp.WriteTo(w) //nolint:errcheck // This will never fail
}
// String returns the status code, string body and errors of url.
//
// it's not safe to use Agent after calling [Agent.String]
func (a *Agent) String() (int, string, []error) {
defer a.release()
code, body, errs := a.bytes()
// TODO: There might be a data race here on body. Maybe use utils.CopyBytes on it?
return code, utils.UnsafeString(body), errs
}
// Struct returns the status code, bytes body and errors of url.
// And bytes body will be unmarshalled to given v.
//
// it's not safe to use Agent after calling [Agent.Struct]
func (a *Agent) Struct(v interface{}) (int, []byte, []error) {
defer a.release()
code, body, errs := a.bytes()
if len(errs) > 0 {
return code, body, errs
}
// TODO: This should only be done once
if a.jsonDecoder == nil {
a.jsonDecoder = json.Unmarshal
}
if err := a.jsonDecoder(body, v); err != nil {
errs = append(errs, err)
}
return code, body, errs
}
func (a *Agent) release() {
if !a.reuse {
ReleaseAgent(a)
} else {
a.errs = a.errs[:0]
}
}
func (a *Agent) reset() {
a.HostClient = nil
a.req.Reset()
a.resp = nil
a.dest = nil
a.timeout = 0
a.args = nil
a.errs = a.errs[:0]
a.debugWriter = nil
a.mw = nil
a.reuse = false
a.parsed = false
a.maxRedirectsCount = 0
a.boundary = ""
a.Name = ""
a.NoDefaultUserAgentHeader = false
for i, ff := range a.formFiles {
if ff.autoRelease {
ReleaseFormFile(ff)
}
a.formFiles[i] = nil
}
a.formFiles = a.formFiles[:0]
}
var (
clientPool sync.Pool
agentPool = sync.Pool{
New: func() interface{} {
return &Agent{req: &Request{}}
},
}
responsePool sync.Pool
argsPool sync.Pool
formFilePool sync.Pool
)
// AcquireClient returns an empty Client instance from client pool.
//
// The returned Client instance may be passed to ReleaseClient when it is
// no longer needed. This allows Client recycling, reduces GC pressure
// and usually improves performance.
func AcquireClient() *Client {
v := clientPool.Get()
if v == nil {
return &Client{}
}
c, ok := v.(*Client)
if !ok {
panic(fmt.Errorf("failed to type-assert to *Client"))
}
return c
}
// ReleaseClient returns c acquired via AcquireClient to client pool.
//
// It is forbidden accessing req and/or its' members after returning
// it to client pool.
func ReleaseClient(c *Client) {
c.UserAgent = ""
c.NoDefaultUserAgentHeader = false
c.JSONEncoder = nil
c.JSONDecoder = nil
clientPool.Put(c)
}
// AcquireAgent returns an empty Agent instance from Agent pool.
//
// The returned Agent instance may be passed to ReleaseAgent when it is
// no longer needed. This allows Agent recycling, reduces GC pressure
// and usually improves performance.
func AcquireAgent() *Agent {
a, ok := agentPool.Get().(*Agent)
if !ok {
panic(fmt.Errorf("failed to type-assert to *Agent"))
}
return a
}
// ReleaseAgent returns a acquired via AcquireAgent to Agent pool.
//
// It is forbidden accessing req and/or its' members after returning
// it to Agent pool.
func ReleaseAgent(a *Agent) {
a.reset()
agentPool.Put(a)
}
// AcquireResponse returns an empty Response instance from response pool.
//
// The returned Response instance may be passed to ReleaseResponse when it is
// no longer needed. This allows Response recycling, reduces GC pressure
// and usually improves performance.
// Copy from fasthttp
func AcquireResponse() *Response {
v := responsePool.Get()
if v == nil {
return &Response{}
}
r, ok := v.(*Response)
if !ok {
panic(fmt.Errorf("failed to type-assert to *Response"))
}
return r
}
// ReleaseResponse return resp acquired via AcquireResponse to response pool.
//
// It is forbidden accessing resp and/or its' members after returning
// it to response pool.
// Copy from fasthttp
func ReleaseResponse(resp *Response) {
resp.Reset()
responsePool.Put(resp)
}
// AcquireArgs returns an empty Args object from the pool.
//
// The returned Args may be returned to the pool with ReleaseArgs
// when no longer needed. This allows reducing GC load.
// Copy from fasthttp
func AcquireArgs() *Args {
v := argsPool.Get()
if v == nil {
return &Args{}
}
a, ok := v.(*Args)
if !ok {
panic(fmt.Errorf("failed to type-assert to *Args"))
}
return a
}
// ReleaseArgs returns the object acquired via AcquireArgs to the pool.
//
// String not access the released Args object, otherwise data races may occur.
// Copy from fasthttp
func ReleaseArgs(a *Args) {
a.Reset()
argsPool.Put(a)
}
// AcquireFormFile returns an empty FormFile object from the pool.
//
// The returned FormFile may be returned to the pool with ReleaseFormFile
// when no longer needed. This allows reducing GC load.
func AcquireFormFile() *FormFile {
v := formFilePool.Get()
if v == nil {
return &FormFile{}
}
ff, ok := v.(*FormFile)
if !ok {
panic(fmt.Errorf("failed to type-assert to *FormFile"))
}
return ff
}
// ReleaseFormFile returns the object acquired via AcquireFormFile to the pool.
//
// String not access the released FormFile object, otherwise data races may occur.
func ReleaseFormFile(ff *FormFile) {
ff.Fieldname = ""
ff.Name = ""