-
Notifications
You must be signed in to change notification settings - Fork 9
/
requests.go
1367 lines (1145 loc) · 37 KB
/
requests.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 requests is a high-level, API-centric HTTP client for Go projects. It
// is meant to provide a more comfortable mechanism to perform requests to HTTP
// APIs (rather than making general requests), and to prevent common mistakes
// made when using net/http directly.
//
// With requests, one must not need to remember to read HTTP responses in full
// (so Go can reuse TCP connections), nor to close response bodies. Handling of
// JSON data - be it in requests or responses - is made easier by way of built-in
// encoders/decoders. An automatic retry mechanism is also included.
//
// The library allows a "DRY" (Dont Repeat Yourself) approach to REST API usage
// by introducing API-specific dependencies into the client object. For example,
// authorization headers and response handlers can be set in the client object,
// and all generated requests will automatically include them.
//
// # Usage
//
// package main
//
// import (
// "fmt"
// "net/http"
// "time"
//
// "github.com/ido50/requests"
// )
//
// const apiURL = "https://my.api.com/v2"
//
// type RequestBody struct {
// Title string `json:"title"`
// Tags []string `json:"tags"`
// Publish bool `json:"publish"`
// }
//
// type ResponseBody struct {
// ID int64 `json:"id"`
// Date time.Time `json:"date"`
// }
//
// func main() {
// client := requests.
// NewClient(apiURL).
// Accept("application/json").
// BasicAuth("user", "pass").
// RetryLimit(3)
//
// var res ResponseBody
//
// err := client.
// NewRequest("POST", "/articles").
// JSONBody(RequestBody{
// Title: "Test Title",
// Tags: []string{"test", "stories"},
// Publish: true,
// }).
// ExpectedStatus(http.StatusCreated).
// Into(&res).
// Run()
// if err != nil {
// panic(err)
// }
//
// fmt.Printf(
// "Created article %d on %s\n",
// res.ID, res.Date.Format(time.RFC3339),
// )
// }
package requests
import (
"bufio"
"bytes"
"compress/gzip"
"compress/zlib"
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"log"
"mime/multipart"
"net"
"net/http"
"net/url"
pathtools "path/filepath"
"reflect"
"strings"
"time"
"unicode"
"go.uber.org/zap"
)
type authType string
const (
noAuth authType = ""
basicAuth authType = "basic"
)
const defaultAuthHeader = "Authorization"
// BodyProcessorFunc is a function that reads a request's body as []byte from a
// provider reader, and writes it to a provided writer, potentially modifying
// it in the process. Such a function can be used to modify request bodies right
// before they are sent.
type BodyProcessorFunc func(r io.Reader, w io.Writer) error
// CompressionAlgorithm denotes compression algorithms supported by the library
// for compressed request bodies.
type CompressionAlgorithm string
const (
// CompressionAlgorithmNone represents no compression
CompressionAlgorithmNone CompressionAlgorithm = ""
// CompressionAlgorithmGzip represents the gzip compression algorithm
CompressionAlgorithmGzip CompressionAlgorithm = "gzip"
// CompressionAlgorithmDeflate represents the deflate compression algorithm
CompressionAlgorithmDeflate CompressionAlgorithm = "deflate"
)
// HTTPClient represents a client for making requests to a web service or
// website. The client includes default options that are relevant for all
// requests (but can be overridden per-request).
type HTTPClient struct {
// base URL for all HTTP requests
baseURL string
// default authentication type for all requests (defaults to no authentication)
authType authType
// default username for all requests
authUser string
// default password for all requests
authPass string
// header name for authentication (defaults to 'Authorization')
authHeader string
// default expected response content type for all requests
accept string
// default timeout for all requests
timeout time.Duration
// default error handler for all requests returning unexpected status
errorHandler ErrorHandlerFunc
// default body handler for requests (when Content-Type is not automatically handled by this library)
bodyHandler BodyHandlerFunc
// default headers for all requests
customHeaders map[string]string
// custom TLS attributes
certPEMBlock []byte
keyPEMBlock []byte
caCert []byte
renegotiationSupport tls.RenegotiationSupport
noTLSVerify bool
// default retry limit for all requests
retryLimit uint8
// optional compression algorithm for all requests
compressionAlgorithm CompressionAlgorithm
// logger to use (only debug messages are printed by the library; defaults to noop logger)
logger *zap.Logger
// underlying net/http client
httpCli *http.Client
}
// HTTPRequest represents a single HTTP request to the web service defined
// in the client.
type HTTPRequest struct {
// the HTTPClient this request belongs to
cli *HTTPClient
// HTTP method/verb to use (GET, POST, PUT, etc.)
method string
// request path (will be appended to the client's base URL)
path string
// URL query parameters for the request
queryParams url.Values
// cookies to send with the HTTP request
cookies []*http.Cookie
// content type of the request's body
contentType string
// bodySrc is a ReadCloser from which the request's body is read by us
bodySrc io.ReadCloser
// bodyDst is a buffer into which the final request body is written (i.e.
// after optional compression or other processing), and which is read by the
// underlying net/http client
bodyDst bytes.Buffer
// bodyProcessorFunc is an optional BodyProcessorFunc to use on when building
// the request's body
bodyProcessorFunc BodyProcessorFunc
// pointer to a variable where the response body will be loaded into
into interface{}
// map of header names to pointers where response header values will be loaded into
headersInto map[string]*string
// pointer where response status code will be loaded
statusInto *int
// pointer where response cookies will be loaded
cookiesInto *[]*http.Cookie
// expected status codes from the server (defaults to any 2xx status)
expectedStatuses []int
// error encountered during building the request
err error
// authentication type for the request (defaults to no authentication)
authType authType
// username for the request
authUser string
// password for the request
authPass string
// header used for authentication (defaults to 'Authorization')
authHeader string
// headers for the request (headers from the client will be used as well, but headers defined here take precedence)
customHeaders map[string]string
// expected response content type
accept string
// timeout for the request
timeout time.Duration
// retry limit for the request
retryLimit uint8
// reject responses whose body size exceeds this value
sizeLimit int64
// optional compression algorithm for the request
compressionAlgorithm CompressionAlgorithm
// error handler for the request if returned status is not the expected one(s)
errorHandler ErrorHandlerFunc
// body handler for the request (when Content-Type is not automatically handled by this library)
bodyHandler BodyHandlerFunc
// logger to use (only debug messages are printed by the library; defaults to noop logger)
logger *zap.Logger
}
// BodyHandlerFunc is a function that processes the response body and reads
// it into the target variable. It receives the status and content type of the
// response (the latter taken from the Content-Type header), the body reader,
// and the target variable (which is whatever was provided to the Into()
// method). It is not necessary to close the body or read it to its entirety.
type BodyHandlerFunc func(
httpStatus int,
contentType string,
body io.Reader,
target interface{},
) error
// ErrorHandlerFunc is similar to BodyHandler, but is called when requests generate
// an unsuccessful response (defined as anything that is not one of the
// expected statuses). It receives the same parameters except "target", and is
// expected to return a formatted error to the client
type ErrorHandlerFunc func(
httpStatus int,
contentType string,
body io.Reader,
) error
var (
// ErrSizeExceeded is the error returned when the size of an HTTP response
// is larger than the set limit
ErrSizeExceeded = errors.New("response size exceeded limit")
// ErrTimeoutReached is the error returned when a request times out
ErrTimeoutReached = errors.New("timeout reached")
// ErrNotAPointer is an error returned when the target variable provided for
// a request's Run method is not a pointer.
ErrNotAPointer = errors.New("target variable is not a string pointer")
// ErrUnsupportedCompression is an error returned when attempting to send
// requests with a compression algorithm unsupported by the library
ErrUnsupportedCompression = errors.New("unsupported compression algorithm")
// ErrUnsupportedBody is an error returned when the value provided to the
// request's Body method is unsupported, i.e. it is not a byte string, a
// string, or a reader
ErrUnsupportedBody = errors.New("unsupported body")
)
// DefaultTimeout is the default timeout for requests made by the library. This
// can be overridden on a per-client and per-request basis.
var DefaultTimeout = 2 * time.Minute
// BaseDelay is the base delay for retrying requests. The library uses a
// backoff strategy, multiplying the delay between each attempt.
var BaseDelay = 2 * time.Second
// NewClient creates a new HTTP client for the API whose base URL is provided.
func NewClient(baseURL string) *HTTPClient {
return &HTTPClient{
baseURL: strings.TrimSuffix(baseURL, "/"),
authType: noAuth,
timeout: DefaultTimeout,
}
}
// Accept sets the response MIME type accepted by the client. Defaults to
// "application/json".
func (cli *HTTPClient) Accept(accept string) *HTTPClient {
cli.accept = accept
return cli
}
// Timeout sets the total timeout for requests made by the client. The default
// timeout is 2 minutes.
func (cli *HTTPClient) Timeout(dur time.Duration) *HTTPClient {
cli.timeout = dur
return cli
}
// RetryLimit sets the maximum amount of times requests that failed due to
// connection issues should be retried. Defaults to 0. Requests are retried with
// a backoff strategy, with the first retry attempt occurring two seconds after
// the original request, and the delay before each subsequent attempt is
// multiplied by two.
func (cli *HTTPClient) RetryLimit(limit uint8) *HTTPClient {
cli.retryLimit = limit
return cli
}
// Logger sets the logger used by the library. Currently, requests uses
// go.uber.org/zap for logging purposes. All log messages are in the DEBUG level.
func (cli *HTTPClient) Logger(logger *zap.Logger) *HTTPClient {
cli.logger = logger
return cli
}
func (cli *HTTPClient) getLogger() *zap.Logger {
if cli.logger == nil {
cli.logger = zap.NewNop()
}
return cli.logger
}
// BasicAuth sets basic authentication headers for all HTTP requests made by the
// client (requests can override this on an individual basis). If a header name
// is provided as the third argument, the authentication data will be set into
// that header instead of the standard "Authorization" header. This is mostly
// useful for Proxy-Authorization or custom headers.
func (cli *HTTPClient) BasicAuth(
user string,
pass string,
headerName ...string,
) *HTTPClient {
cli.authType = "basic"
cli.authUser = user
cli.authPass = pass
if len(headerName) > 0 {
cli.authHeader = headerName[0]
} else {
cli.authHeader = defaultAuthHeader
}
return cli
}
// Header sets a common header value for all requests made by the client.
func (cli *HTTPClient) Header(key, value string) *HTTPClient {
if cli.customHeaders == nil {
cli.customHeaders = make(map[string]string)
}
cli.customHeaders[key] = value
return cli
}
// CompressWith sets a compression algorithm to apply to all request bodies.
// Compression is optional, in that if it fails, for any reason, requests will
// not fail, but instead be sent without compression.
// Note that there is no need to use this to support decompression of responses,
// the library handles decompressions automatically.
func (cli *HTTPClient) CompressWith(alg CompressionAlgorithm) *HTTPClient {
cli.compressionAlgorithm = alg
return cli
}
// ErrorHandler sets a custom handler function for all requests made by the
// client. Whenever a request is answered with an error response (or optionally
// in an unexpected status), the handler is called. This allows parsing API
// error structures so more information can be returned in case of failure.
func (cli *HTTPClient) ErrorHandler(handler ErrorHandlerFunc) *HTTPClient {
cli.errorHandler = handler
return cli
}
// BodyHandler sets a customer handler function for all requests made by the
// client. If provided, the handler will be called with the response status,
// content type, and body reader. This allows customizing the way response
// bodies are parsed, for example if the API does not use JSON serialization.
// Usually, the library's internal handler is sufficient for API usage.
func (cli *HTTPClient) BodyHandler(handler BodyHandlerFunc) *HTTPClient {
cli.bodyHandler = handler
return cli
}
// CustomHTTPClient sets a custom HTTP client for the underlaying net layer
func (cli *HTTPClient) CustomHTTPClient(cl *http.Client) *HTTPClient {
cli.httpCli = cl
return cli
}
// NoTLSVerify allows ignoring invalid or self-signed TLS certificates presented
// by HTTPS servers.
func (cli *HTTPClient) NoTLSVerify(enabled bool) *HTTPClient {
if cli.httpCli != nil {
transport, ok := cli.httpCli.Transport.(*http.Transport)
if ok {
transport.TLSClientConfig.InsecureSkipVerify = enabled
} else {
// just nil out the client so a new one is created
cli.httpCli = nil
}
}
cli.noTLSVerify = enabled
return cli
}
// SetRenegotiation allows setting the TLS renegotiation level. See crypto/tls
// for more information.
func (cli *HTTPClient) SetRenegotiation(support tls.RenegotiationSupport) *HTTPClient {
cli.renegotiationSupport = support
return cli
}
// SetTLS allows creating a custom TLS transport. Often combined with
// SetRenegotiation.
func (cli *HTTPClient) SetTLS(
certPEMBlock, keyPEMBlock, caCert []byte,
) *HTTPClient {
cli.caCert = caCert
cli.keyPEMBlock = keyPEMBlock
cli.certPEMBlock = certPEMBlock
return cli
}
// Do performs an HTTP request represented as a net/http.Request object. This
// method was added so that an HTTPClient object will implement a common interface
// for HTTP clients. Generally, there is no need to use this method.
func (cli *HTTPClient) Do(req *http.Request) (*http.Response, error) {
ctx := context.Background()
if cli.timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, cli.timeout)
defer cancel()
}
return cli.retryRequest(
ctx,
cli.logger,
req,
nil,
cli.retryLimit+1,
)
}
func (cli *HTTPClient) retryRequest(
ctx context.Context,
logger *zap.Logger,
req *http.Request,
body *bytes.Buffer,
attempts uint8,
) (res *http.Response, err error) {
if cli.httpCli == nil {
if cli.certPEMBlock == nil {
cli.httpCli = &http.Client{
Transport: defaultTransport(cli.noTLSVerify, cli.renegotiationSupport),
}
} else {
cli.httpCli = &http.Client{
Transport: tlsTransport(
cli.certPEMBlock,
cli.keyPEMBlock,
cli.caCert,
cli.noTLSVerify,
cli.renegotiationSupport,
),
}
}
}
if logger == nil {
logger = zap.NewNop()
}
delay := BaseDelay
for attempt := uint8(1); attempt <= attempts; attempt++ {
if body != nil {
req.Body = io.NopCloser(body)
}
req = req.WithContext(ctx)
res, err = cli.httpCli.Do(req)
if err != nil {
if urlErr, ok := err.(*url.Error); ok {
if errors.Is(urlErr.Err, context.DeadlineExceeded) {
err = ErrTimeoutReached
}
}
}
// we retry requests if an error is returned from net/http, or if
// the status of the response is 502, 503, 429 or 504, which are all proxy
// errors that may be temporary
if err == nil &&
res.StatusCode != http.StatusBadGateway &&
res.StatusCode != http.StatusServiceUnavailable &&
res.StatusCode != http.StatusTooManyRequests &&
res.StatusCode != http.StatusGatewayTimeout {
break
}
// failed this attempt, sleep 2*attempt seconds and try again
if attempt < attempts {
// make sure to close the body
if res != nil {
closeBody(res.Body)
}
logger.Debug(
"Request failed, will retry",
zap.Uint8("attempt", attempt),
zap.Uint8("limit", attempts),
zap.Duration("delay", delay),
zap.Error(err),
)
time.Sleep(delay)
delay *= 2
}
}
return res, err
}
/******************************************************************************/
/* REQUESTS */
/******************************************************************************/
// NewRequest creates a new request object. Requests are progressively
// composed using a builder/method-chain pattern. The HTTP method and path
// within the API must be provided. Remember that the client already includes
// a base URL, so the request URL will be a concatenation of the base URL and
// the provided path. `path` can be empty.
func (cli *HTTPClient) NewRequest(method, path string) *HTTPRequest {
return &HTTPRequest{
cli: cli,
path: path,
method: method,
logger: cli.getLogger().With(
zap.String("path", path),
zap.String("method", method),
),
}
}
// QueryParam adds a query parameter and value to the request.
func (req *HTTPRequest) QueryParam(key, value string) *HTTPRequest {
if req.queryParams == nil {
req.queryParams = url.Values{}
}
req.queryParams.Add(key, value)
return req
}
// Cookie sets a cookie for the request.
func (req *HTTPRequest) Cookie(cookie *http.Cookie) *HTTPRequest {
req.cookies = append(req.cookies, cookie)
return req
}
// ReaderBody sets a custom body for the request from an io.ReadCloser,
// io.Reader, []byte or string. The content type of the data must be provided.
func (req *HTTPRequest) Body(body interface{}, contentType string) *HTTPRequest {
if rc, ok := body.(io.ReadCloser); ok {
req.bodySrc = rc
} else if r, ok := body.(io.Reader); ok {
req.bodySrc = io.NopCloser(r)
} else if b, ok := body.([]byte); ok {
req.bodySrc = io.NopCloser(bytes.NewReader(b))
} else if s, ok := body.(string); ok {
req.bodySrc = io.NopCloser(strings.NewReader(s))
} else {
req.err = ErrUnsupportedBody
}
req.contentType = contentType
return req
}
// JSONBody encodes the provided Go value into JSON and sets it as the request
// body.
func (req *HTTPRequest) JSONBody(body interface{}) *HTTPRequest {
encodedBody, err := json.Marshal(body)
if err != nil {
req.err = fmt.Errorf("failed encoding JSON body: %w", err)
}
return req.Body(encodedBody, "application/json; charset=UTF-8")
}
// FileBody sets the request body to be read from the provided filesystem and
// file path. The content type must be provided.
func (req *HTTPRequest) FileBody(fsys fs.FS, filepath, contentType string) *HTTPRequest {
var err error
req.bodySrc, err = fsys.Open(filepath)
if err != nil {
req.err = fmt.Errorf("failed opening body file %q: %w", filepath, err)
}
req.contentType = contentType
return req
}
// MultipartBody creates a multipart/form-data body from one or more sources,
// which may be file objects, bytes, strings or any reader.
func (req *HTTPRequest) MultipartBody(srcs ...*multipartSrc) *HTTPRequest {
var output bytes.Buffer
writer := multipart.NewWriter(&output)
for _, src := range srcs {
formFile, err := writer.CreateFormFile(src.fieldname, src.filename)
if err != nil {
req.err = fmt.Errorf(
"failed creating form file %q: %w",
src.fieldname, err,
)
return req
}
var srcReader io.ReadCloser
if src.filepath != "" {
srcReader, err = src.filesystem.Open(src.filepath)
if err != nil {
req.err = fmt.Errorf(
"failed opening source file %q: %w",
src.filepath, err,
)
return req
}
} else {
if rc, ok := src.body.(io.ReadCloser); ok {
srcReader = rc
} else if r, ok := src.body.(io.Reader); ok {
srcReader = io.NopCloser(r)
} else if b, ok := src.body.([]byte); ok {
srcReader = io.NopCloser(bytes.NewReader(b))
} else if s, ok := src.body.(string); ok {
srcReader = io.NopCloser(strings.NewReader(s))
} else {
req.err = ErrUnsupportedBody
return req
}
}
_, err = io.Copy(formFile, srcReader)
srcReader.Close()
if err != nil {
req.err = fmt.Errorf(
"failed reading form file %q: %w",
src.fieldname, err,
)
return req
}
}
err := writer.Close()
if err != nil {
req.err = fmt.Errorf("failed closing multipart message: %w", err)
return req
}
return req.Body(&output, writer.FormDataContentType())
}
type multipartSrc struct {
fieldname string
filename string
body interface{}
filesystem fs.FS
filepath string
}
// MultipartPart adds a new part to a multipart request with the provided field
// name, file name, and body, which may be a []byte value, a string, or a reader.
func MultipartPart(fieldname, filename string, body interface{}) *multipartSrc {
return &multipartSrc{fieldname: fieldname, filename: filename, body: body}
}
// MultipartFile adds a new part to a multipart request from the provided file
// in a filesystem.
func MultipartFile(fieldname string, fsys fs.FS, filepath string) *multipartSrc {
return &multipartSrc{
fieldname: fieldname,
filename: pathtools.Base(filepath),
filesystem: fsys,
filepath: filepath,
}
}
// ReqBodyProcessor adds a BodyProcessorFunc to the request. This function will
// be called right before the request is issued and can be used to modify the
// request body. The processor function MUST read AND write the entire body, and
// should not close it.
func (req *HTTPRequest) ReqBodyProcessor(fn BodyProcessorFunc) *HTTPRequest {
req.bodyProcessorFunc = fn
return req
}
// Accept sets the accepted MIME type for the request. This takes precedence
// over the MIME type provided to the client object itself.
func (req *HTTPRequest) Accept(accept string) *HTTPRequest {
req.accept = accept
return req
}
// Timeout sets the timeout for the request. This takes precedence over the
// timeout provided to the client object itself.
func (req *HTTPRequest) Timeout(dur time.Duration) *HTTPRequest {
req.timeout = dur
return req
}
// RetryLimit sets the maximum amount of retries for the request. This takes
// precedence over the limit provided to the client object itself.
func (req *HTTPRequest) RetryLimit(limit uint8) *HTTPRequest {
req.retryLimit = limit
return req
}
// SizeLimit allows limiting the size of response bodies accepted by the client.
// If the response size is larger than the limit, `ErrSizeExceeded` will be
// returned.
func (req *HTTPRequest) SizeLimit(limit int64) *HTTPRequest {
req.sizeLimit = limit
return req
}
// Into sets the target variable to which the response body should be parsed.
// If the API returns JSON, then this should be a pointer to a struct that
// represents the expected format. If using a custom body handler, this variable
// will be provided to the handler.
func (req *HTTPRequest) Into(into interface{}) *HTTPRequest {
req.into = into
return req
}
// HeaderInto allows storing the value of a header from the response into a
// string variable. Since the requests library is made to quickly perform
// requests to REST APIs, and only a small number of response headers is usually
// read by application code (if at all), there is no response object that allows
// viewing headers. Therefore, any code that is interested in reading a response
// header must declare that in advance and provide a target variable.
func (req *HTTPRequest) HeaderInto(header string, into *string) *HTTPRequest {
if req.headersInto == nil {
req.headersInto = make(map[string]*string)
}
req.headersInto[header] = into
return req
}
// StatusInto allows storing the status of the response into a variable. The
// same comments as for HeaderInto apply here as well.
func (req *HTTPRequest) StatusInto(into *int) *HTTPRequest {
req.statusInto = into
return req
}
// CookiesInto allows storing cookies in the response into a slice of cookies.
// The same comments as for HeaderInto apply here as well.
func (req *HTTPRequest) CookiesInto(into *[]*http.Cookie) *HTTPRequest {
req.cookiesInto = into
return req
}
// ExpectedStatus sets the HTTP status that the application expects to receive
// for the request. If the status received is different than the expected status,
// the library will return an error, and the error handler will be executed.
func (req *HTTPRequest) ExpectedStatus(status int) *HTTPRequest {
req.expectedStatuses = []int{status}
return req
}
// ExpectedStatuses is the same as ExpectedStatus, but allows setting multiple
// expected statuses.
func (req *HTTPRequest) ExpectedStatuses(statuses ...int) *HTTPRequest {
req.expectedStatuses = statuses
return req
}
// BasicAuth allows setting basic authentication header for the request.
// Usually, this will be done on the client object rather than the request
// object, but this method allows overriding authentication for specific
// requests.
func (req *HTTPRequest) BasicAuth(
user, pass string,
headerName ...string,
) *HTTPRequest {
req.authType = "basic"
req.authUser = user
req.authPass = pass
if len(headerName) > 0 {
req.authHeader = headerName[0]
} else {
req.authHeader = defaultAuthHeader
}
return req
}
// Header sets the value of a header for the request.
func (req *HTTPRequest) Header(key, value string) *HTTPRequest {
if req.customHeaders == nil {
req.customHeaders = make(map[string]string)
}
req.customHeaders[key] = value
return req
}
// CompressWith sets a compression algorithm to apply to all request bodies.
// Compression is optional, in that if it fails, for any reason, requests will
// not fail, but instead be sent without compression.
// Note that there is no need to use this to support decompression of responses,
// the library handles decompressions automatically.
func (req *HTTPRequest) CompressWith(alg CompressionAlgorithm) *HTTPRequest {
req.compressionAlgorithm = alg
return req
}
// ErrorHandler sets a custom error handler for the request.
func (req *HTTPRequest) ErrorHandler(handler ErrorHandlerFunc) *HTTPRequest {
req.errorHandler = handler
return req
}
// BodyHandler sets a custom body handler for the request.
func (req *HTTPRequest) BodyHandler(handler BodyHandlerFunc) *HTTPRequest {
req.bodyHandler = handler
return req
}
// Run finalizes the request and executes it. The returned error will be `nil`
// only if the request was successfully created, sent and a successful (or
// expected) status code was returned from the server.
func (req *HTTPRequest) Run() error {
return req.RunContext(context.Background())
}
// RunContext is the same as Run, but executes the request with the provided
// context value.
func (req *HTTPRequest) RunContext(ctx context.Context) error {
res, cancel, err := req.execute(ctx)
if err != nil {
return err
}
if cancel != nil {
defer cancel()
}
// make sure to read the entire body and close the request once we're
// done, this is important in order to reuse connections and prevent
// connection leaks
defer closeBody(res.Body)
// make sure response size does not exceed the limit
if req.sizeLimit > 0 && res.ContentLength > req.sizeLimit {
return ErrSizeExceeded
}
return req.parseResponse(res)
}
// Issue the request, expecting a text/event-stream response, and subscribe to
// that stream. Events (well, messages) from the server will be sent as-is to
// the provided channel. When all messages have been read, the channel is
// automatically closed.
func (req *HTTPRequest) Subscribe(ctx context.Context, messages chan []byte) error {
req.Accept("text/event-stream")
res, cancel, err := req.execute(ctx)
if err != nil {
return err
}
err = req.parseResponse(res)
if err != nil {
return err
}
go func() {
if cancel != nil {
defer cancel()
}
defer closeBody(res.Body)
br := bufio.NewReader(res.Body)
for {
bs, err := br.ReadBytes('\n')
if err != nil && err != io.EOF {
log.Printf("ERROR: %s", err)
break
}
if len(bs) < 2 {
continue
}
messages <- bs
if err == io.EOF {
break
}
}
close(messages)
}()
return nil
}
func (req *HTTPRequest) execute(ctx context.Context) (
res *http.Response,
cancel context.CancelFunc,
err error,
) {
// did we fail during building the request? if so, return the error
if req.err != nil {
return nil, nil, req.err
}
// create the request
r, err := req.createRequest()
if err != nil {
return nil, nil, err
}
// how many attempts are we gonna make?
var attempts = uint8(1)
if req.retryLimit > 0 {
attempts += req.retryLimit
} else if req.cli.retryLimit > 0 {
attempts += req.cli.retryLimit