-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
732 lines (630 loc) · 18.4 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
package requests
import (
"bytes"
"context"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"slices"
"strings"
"time"
"github.com/google/go-querystring/query"
)
// RequestBuilder facilitates building and executing HTTP requests
type RequestBuilder struct {
client *Client
method string
path string
headers *http.Header
cookies []*http.Cookie
queries url.Values
pathParams map[string]string
formFields url.Values
formFiles []*File
boundary string
bodyData interface{}
timeout time.Duration
middlewares []Middleware
maxRetries int
retryStrategy BackoffStrategy
retryIf RetryIfFunc
auth AuthMethod
stream StreamCallback
streamErr StreamErrCallback
streamDone StreamDoneCallback
}
// NewRequestBuilder creates a new RequestBuilder with default settings
func (c *Client) NewRequestBuilder(method, path string) *RequestBuilder {
return &RequestBuilder{
client: c,
method: method,
path: path,
queries: url.Values{},
headers: &http.Header{},
}
}
// AddMiddleware adds a middleware to the request.
func (b *RequestBuilder) AddMiddleware(middlewares ...Middleware) {
if b.middlewares == nil {
b.middlewares = []Middleware{}
}
b.middlewares = append(b.middlewares, middlewares...)
}
// Method sets the HTTP method for the request.
func (b *RequestBuilder) Method(method string) *RequestBuilder {
b.method = method
return b
}
// Path sets the URL path for the request.
func (b *RequestBuilder) Path(path string) *RequestBuilder {
b.path = path
return b
}
// PathParams sets multiple path params fields and their values at one go in the RequestBuilder instance.
func (b *RequestBuilder) PathParams(params map[string]string) *RequestBuilder {
if b.pathParams == nil {
b.pathParams = map[string]string{}
}
for key, value := range params {
b.pathParams[key] = value
}
return b
}
// PathParam sets a single path param field and its value in the RequestBuilder instance.
func (b *RequestBuilder) PathParam(key, value string) *RequestBuilder {
if b.pathParams == nil {
b.pathParams = map[string]string{}
}
b.pathParams[key] = value
return b
}
// DelPathParam removes one or more path params fields from the RequestBuilder instance.
func (b *RequestBuilder) DelPathParam(key ...string) *RequestBuilder {
if b.pathParams != nil {
for _, k := range key {
delete(b.pathParams, k)
}
}
return b
}
// preparePath replaces path parameters in the URL path.
func (b *RequestBuilder) preparePath() string {
if b.pathParams == nil {
return b.path
}
preparedPath := b.path
for key, value := range b.pathParams {
placeholder := "{" + key + "}"
preparedPath = strings.ReplaceAll(preparedPath, placeholder, url.PathEscape(value))
}
return preparedPath
}
// Queries adds query parameters to the request
func (b *RequestBuilder) Queries(params url.Values) *RequestBuilder {
for key, values := range params {
for _, value := range values {
b.queries.Add(key, value)
}
}
return b
}
// Query adds a single query parameter to the request
func (b *RequestBuilder) Query(key, value string) *RequestBuilder {
b.queries.Add(key, value)
return b
}
// DelQuery removes one or more query parameters from the request.
func (b *RequestBuilder) DelQuery(key ...string) *RequestBuilder {
for _, k := range key {
b.queries.Del(k)
}
return b
}
// QueriesStruct adds query parameters to the request based on a struct tagged with url tags.
func (b *RequestBuilder) QueriesStruct(queryStruct interface{}) *RequestBuilder {
values, _ := query.Values(queryStruct) // Safely ignore error for simplicity
for key, value := range values {
for _, v := range value {
b.queries.Add(key, v)
}
}
return b
}
// Headers set headers to the request
func (b *RequestBuilder) Headers(headers http.Header) *RequestBuilder {
for key, values := range headers {
for _, value := range values {
b.headers.Set(key, value)
}
}
return b
}
// Header sets (or replaces) a header in the request.
func (b *RequestBuilder) Header(key, value string) *RequestBuilder {
b.headers.Set(key, value)
return b
}
// AddHeader adds a header to the request.
func (b *RequestBuilder) AddHeader(key, value string) *RequestBuilder {
b.headers.Add(key, value)
return b
}
// DelHeader removes one or more headers from the request.
func (b *RequestBuilder) DelHeader(key ...string) *RequestBuilder {
for _, k := range key {
b.headers.Del(k)
}
return b
}
// Cookies method for map
func (b *RequestBuilder) Cookies(cookies map[string]string) *RequestBuilder {
for key, value := range cookies {
b.Cookie(key, value)
}
return b
}
// Cookie adds a cookie to the request.
func (b *RequestBuilder) Cookie(key, value string) *RequestBuilder {
if b.cookies == nil {
b.cookies = []*http.Cookie{}
}
b.cookies = append(b.cookies, &http.Cookie{Name: key, Value: value})
return b
}
// DelCookie removes one or more cookies from the request.
func (b *RequestBuilder) DelCookie(key ...string) *RequestBuilder {
if b.cookies != nil {
for i, cookie := range b.cookies {
if slices.Contains(key, cookie.Name) {
b.cookies = append(b.cookies[:i], b.cookies[i+1:]...)
}
}
}
return b
}
// ContentType sets the Content-Type header for the request.
func (b *RequestBuilder) ContentType(contentType string) *RequestBuilder {
b.headers.Set("Content-Type", contentType)
return b
}
// Accept sets the Accept header for the request.
func (b *RequestBuilder) Accept(accept string) *RequestBuilder {
b.headers.Set("Accept", accept)
return b
}
// UserAgent sets the User-Agent header for the request.
func (b *RequestBuilder) UserAgent(userAgent string) *RequestBuilder {
b.headers.Set("User-Agent", userAgent)
return b
}
// Referer sets the Referer header for the request.
func (b *RequestBuilder) Referer(referer string) *RequestBuilder {
b.headers.Set("Referer", referer)
return b
}
// Auth applies an authentication method to the request.
func (b *RequestBuilder) Auth(auth AuthMethod) *RequestBuilder {
if auth.Valid() {
b.auth = auth
}
return b
}
// Form sets form fields and files for the request
func (b *RequestBuilder) Form(v any) *RequestBuilder {
formFields, formFiles, err := parseForm(v)
if err != nil {
if b.client.Logger != nil {
b.client.Logger.Errorf("Error parsing form: %v", err)
}
return b
}
if formFields != nil {
b.formFields = formFields
}
if formFiles != nil {
b.formFiles = formFiles
}
return b
}
// FormFields sets multiple form fields at once
func (b *RequestBuilder) FormFields(fields any) *RequestBuilder {
if b.formFields == nil {
b.formFields = url.Values{}
}
values, err := parseFormFields(fields)
if err != nil {
if b.client.Logger != nil {
b.client.Logger.Errorf("Error parsing form fields: %v", err)
}
return b
}
for key, value := range values {
for _, v := range value {
b.formFields.Add(key, v)
}
}
return b
}
// FormField adds or updates a form field
func (b *RequestBuilder) FormField(key, val string) *RequestBuilder {
if b.formFields == nil {
b.formFields = url.Values{}
}
b.formFields.Add(key, val)
return b
}
// DelFormField removes one or more form fields
func (b *RequestBuilder) DelFormField(key ...string) *RequestBuilder {
if b.formFields != nil {
for _, k := range key {
b.formFields.Del(k)
}
}
return b
}
// Files sets multiple files at once
func (b *RequestBuilder) Files(files ...*File) *RequestBuilder {
if b.formFiles == nil {
b.formFiles = []*File{}
}
b.formFiles = append(b.formFiles, files...)
return b
}
// File adds a file to the request
func (b *RequestBuilder) File(key, filename string, content io.ReadCloser) *RequestBuilder {
if b.formFiles == nil {
b.formFiles = []*File{}
}
b.formFiles = append(b.formFiles, &File{
Name: key,
FileName: filename,
Content: content,
})
return b
}
// DelFile removes one or more files from the request
func (b *RequestBuilder) DelFile(key ...string) *RequestBuilder {
if b.formFiles != nil {
for i, file := range b.formFiles {
if slices.Contains(key, file.Name) {
b.formFiles = append(b.formFiles[:i], b.formFiles[i+1:]...)
}
}
}
return b
}
// Body sets the request body
func (b *RequestBuilder) Body(body interface{}) *RequestBuilder {
b.bodyData = body
return b
}
// JSONBody sets the request body as JSON
func (b *RequestBuilder) JSONBody(v interface{}) *RequestBuilder {
b.bodyData = v
b.headers.Set("Content-Type", "application/json")
return b
}
// XMLBody sets the request body as XML
func (b *RequestBuilder) XMLBody(v interface{}) *RequestBuilder {
b.bodyData = v
b.headers.Set("Content-Type", "application/xml")
return b
}
// YAMLBody sets the request body as YAML
func (b *RequestBuilder) YAMLBody(v interface{}) *RequestBuilder {
b.bodyData = v
b.headers.Set("Content-Type", "application/yaml")
return b
}
// TextBody sets the request body as plain text
func (b *RequestBuilder) TextBody(v string) *RequestBuilder {
b.bodyData = v
b.headers.Set("Content-Type", "text/plain")
return b
}
// RawBody sets the request body as raw bytes
func (b *RequestBuilder) RawBody(v []byte) *RequestBuilder {
b.bodyData = v
return b
}
// Timeout sets the request timeout
func (b *RequestBuilder) Timeout(timeout time.Duration) *RequestBuilder {
b.timeout = timeout
return b
}
// MaxRetries sets the maximum number of retry attempts
func (b *RequestBuilder) MaxRetries(maxRetries int) *RequestBuilder {
b.maxRetries = maxRetries
return b
}
// RetryStrategy sets the backoff strategy for retries
func (b *RequestBuilder) RetryStrategy(strategy BackoffStrategy) *RequestBuilder {
b.retryStrategy = strategy
return b
}
// RetryIf sets the custom retry condition function
func (b *RequestBuilder) RetryIf(retryIf RetryIfFunc) *RequestBuilder {
b.retryIf = retryIf
return b
}
func (b *RequestBuilder) do(ctx context.Context, req *http.Request) (*http.Response, error) {
finalHandler := MiddlewareHandlerFunc(func(req *http.Request) (*http.Response, error) {
var maxRetries = b.client.MaxRetries
if b.maxRetries > 0 {
maxRetries = b.maxRetries
}
var retryStrategy = b.client.RetryStrategy
if b.retryStrategy != nil {
retryStrategy = b.retryStrategy
}
var retryIf = b.client.RetryIf
if b.retryIf != nil {
retryIf = b.retryIf
}
if maxRetries < 1 {
return b.client.HTTPClient.Do(req) // Single request, no retries
}
var lastErr error
var resp *http.Response
for attempt := 0; attempt <= maxRetries; attempt++ {
resp, lastErr = b.client.HTTPClient.Do(req)
// Determine if a retry is needed
shouldRetry := lastErr != nil || (resp != nil && retryIf != nil && retryIf(req, resp, lastErr))
if !shouldRetry || attempt == maxRetries {
if lastErr != nil {
if b.client.Logger != nil {
b.client.Logger.Errorf("Error after %d attempts: %v", attempt+1, lastErr)
}
}
break
}
if resp != nil {
if err := resp.Body.Close(); err != nil {
if b.client.Logger != nil {
b.client.Logger.Errorf("Error closing response body: %v", err)
}
}
}
// Logging retry decision
if b.client.Logger != nil {
b.client.Logger.Infof("Retrying request (attempt %d) after backoff", attempt+1)
}
// Logging context cancellation as an error condition
select {
case <-ctx.Done():
if b.client.Logger != nil {
b.client.Logger.Errorf("Request canceled or timed out: %v", ctx.Err())
}
return nil, ctx.Err()
case <-time.After(retryStrategy(attempt)):
// Backoff before retrying
}
}
return resp, lastErr
})
if b.middlewares != nil {
for i := len(b.middlewares) - 1; i >= 0; i-- {
finalHandler = b.middlewares[i](finalHandler)
}
}
if b.client.Middlewares != nil {
for i := len(b.client.Middlewares) - 1; i >= 0; i-- {
finalHandler = b.client.Middlewares[i](finalHandler)
}
}
return finalHandler(req)
}
// Stream sets the stream callback for the request
func (b *RequestBuilder) Stream(callback StreamCallback) *RequestBuilder {
b.stream = callback
return b
}
// StreamErr sets the error callback for the request.
func (b *RequestBuilder) StreamErr(callback StreamErrCallback) *RequestBuilder {
b.streamErr = callback
return b
}
// StreamDone sets the done callback for the request.
func (b *RequestBuilder) StreamDone(callback StreamDoneCallback) *RequestBuilder {
b.streamDone = callback
return b
}
// Send executes the HTTP request.
func (b *RequestBuilder) Send(ctx context.Context) (*Response, error) {
var body io.Reader
var contentType string
var err error
switch {
case len(b.formFiles) > 0:
// If the request includes files, indicating multipart/form-data encoding is required.
body, contentType, err = b.prepareMultipartBody()
case len(b.formFields) > 0:
// For form fields without files, use application/x-www-form-urlencoded encoding.
body, contentType = b.prepareFormFieldsBody()
case b.bodyData != nil:
// Fallback to handling as per original logic for JSON, XML, etc.
body, contentType, err = b.prepareBodyBasedOnContentType()
}
if err != nil {
if b.client.Logger != nil {
b.client.Logger.Errorf("Error preparing request body: %v", err)
}
return nil, err
}
if contentType != "" {
// Set the Content-Type header based on the determined contentType.
b.headers.Set("Content-Type", contentType)
}
// Parse the complete URL first to handle any modifications needed.
parsedURL, err := url.Parse(b.client.BaseURL + b.preparePath())
if err != nil {
if b.client.Logger != nil {
b.client.Logger.Errorf("Error parsing URL: %v", err)
}
return nil, err
}
// Combine query parameters from both the URL and the Query method.
query := parsedURL.Query()
for key, values := range b.queries {
for _, value := range values {
query.Set(key, value) // Add new values, preserving existing ones.
}
}
parsedURL.RawQuery = query.Encode()
// Create a context with a timeout if one is not already set.
var cancel context.CancelFunc
if _, ok := ctx.Deadline(); !ok {
if b.timeout > 0 {
ctx, cancel = context.WithTimeout(ctx, b.timeout)
defer cancel()
}
}
// Create the HTTP request with the fully prepared URL, including query parameters.
req, err := http.NewRequestWithContext(ctx, b.method, parsedURL.String(), body)
if err != nil {
if b.client.Logger != nil {
b.client.Logger.Errorf("Error creating request: %v", err)
}
return nil, fmt.Errorf("%w: %v", ErrRequestCreationFailed, err) //nolint:errorlint
}
if b.auth != nil {
b.auth.Apply(req)
} else if b.client.auth != nil {
b.client.auth.Apply(req)
}
// Set the headers from the client and the request builder.
if b.client.Headers != nil {
for key := range *b.client.Headers {
values := (*b.client.Headers)[key]
for _, value := range values {
req.Header.Add(key, value)
}
}
}
if b.headers != nil {
for key := range *b.headers {
values := (*b.headers)[key]
for _, value := range values {
req.Header.Add(key, value)
}
}
}
// Merge cookies from the client and the request builder.
if b.client.Cookies != nil {
for _, cookie := range b.client.Cookies {
req.AddCookie(cookie)
}
}
if b.cookies != nil {
for _, cookie := range b.cookies {
req.AddCookie(cookie)
}
}
// Execute the HTTP request.
resp, err := b.do(ctx, req)
if err != nil {
if b.client.Logger != nil {
b.client.Logger.Errorf("Error executing request: %v", err)
}
if resp != nil {
_ = resp.Body.Close()
}
return nil, err
}
if resp == nil {
if b.client.Logger != nil {
b.client.Logger.Errorf("Response is nil")
}
return nil, fmt.Errorf("%w: %v", ErrResponseNil, err) //nolint:errorlint
}
// Wrap and return the response.
return NewResponse(ctx, resp, b.client, b.stream, b.streamErr, b.streamDone)
}
func (b *RequestBuilder) prepareMultipartBody() (io.Reader, string, error) {
var buf bytes.Buffer
writer := multipart.NewWriter(&buf)
// if a custom boundary is set, use it
if b.boundary != "" {
if err := writer.SetBoundary(b.boundary); err != nil {
return nil, "", fmt.Errorf("setting custom boundary failed: %w", err)
}
}
// add form fields
for key, vals := range b.formFields {
for _, val := range vals {
if err := writer.WriteField(key, val); err != nil {
return nil, "", fmt.Errorf("writing form field failed: %w", err)
}
}
}
// add form files
for _, file := range b.formFiles {
// create a new multipart part for the file
part, err := writer.CreateFormFile(file.Name, file.FileName)
if err != nil {
return nil, "", fmt.Errorf("creating form file failed: %w", err)
}
// copy the file content to the part
if _, err = io.Copy(part, file.Content); err != nil {
return nil, "", fmt.Errorf("copying file content failed: %w", err)
}
// close the file content if it's a closer
if closer, ok := file.Content.(io.Closer); ok {
if err = closer.Close(); err != nil {
return nil, "", fmt.Errorf("closing file content failed: %w", err)
}
}
}
// close the multipart writer
if err := writer.Close(); err != nil {
return nil, "", fmt.Errorf("closing multipart writer failed: %w", err)
}
return &buf, writer.FormDataContentType(), nil
}
func (b *RequestBuilder) prepareFormFieldsBody() (io.Reader, string) {
// Encode formFields as URL-encoded string
data := b.formFields.Encode()
return strings.NewReader(data), "application/x-www-form-urlencoded"
}
func (b *RequestBuilder) prepareBodyBasedOnContentType() (io.Reader, string, error) {
// Determine and prepare the body based on the specific Content-Type
contentType := b.headers.Get("Content-Type")
if contentType == "" && b.bodyData != nil {
switch b.bodyData.(type) {
case url.Values, map[string][]string, map[string]string:
contentType = "application/x-www-form-urlencoded"
case map[string]interface{}, []interface{}, struct{}:
contentType = "application/json"
case string, []byte:
contentType = "text/plain"
}
// Set the inferred Content-Type
b.headers.Set("Content-Type", contentType)
}
var body io.Reader
var err error
switch contentType {
case "application/json":
body, err = b.client.JSONEncoder.Encode(b.bodyData)
case "application/xml":
body, err = b.client.XMLEncoder.Encode(b.bodyData)
case "application/yaml":
body, err = b.client.YAMLEncoder.Encode(b.bodyData)
case "application/x-www-form-urlencoded":
body, err = DefaultFormEncoder.Encode(b.bodyData)
case "text/plain", "application/octet-stream":
switch data := b.bodyData.(type) {
case string:
body = strings.NewReader(data)
case []byte:
body = bytes.NewReader(data)
default:
err = fmt.Errorf("%w: %s", ErrUnsupportedContentType, contentType)
}
default:
err = fmt.Errorf("%w: %s", ErrUnsupportedContentType, contentType)
}
return body, contentType, err
}