-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.go
More file actions
734 lines (650 loc) · 24.1 KB
/
request.go
File metadata and controls
734 lines (650 loc) · 24.1 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
package relay
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/textproto"
"net/url"
"strings"
"time"
"github.com/jhonsferg/relay/internal/pool"
)
// MultipartField represents a single part in a multipart/form-data request.
// Set FileName to create a file part; leave it empty for a plain form field.
// Reader takes precedence over Content when both are set.
// ContentType overrides the default application/octet-stream for file parts.
type MultipartField struct {
// FieldName is the form field name (the name attribute in HTML).
FieldName string
// FileName is the filename reported to the server. A non-empty value
// creates a file part; an empty value creates a plain form field.
FileName string
// ContentType is an optional MIME type for file parts.
// When empty, multipart.Writer uses application/octet-stream.
ContentType string
// Content holds in-memory file or field data. Use Reader instead for
// streaming sources such as os.File to avoid loading the whole file.
Content []byte
// Reader is a streaming data source. Takes precedence over Content when
// both are non-nil. The caller is responsible for closing it after Execute.
Reader io.Reader
}
// Request is a fluent builder for a single HTTP call. All With* methods return
// the receiver so they can be chained without intermediate variables.
//
// A Request must not be shared between goroutines after it is passed to
// [Client.Execute].
type Request struct {
// method is the HTTP verb (GET, POST, …).
method string
// rawURL is the URL as provided by the caller. It may be a full URL or a
// path relative to [Config.BaseURL].
rawURL string
// headers are per-request HTTP headers. They take precedence over
// [Config.DefaultHeaders].
headers map[string]string
// query holds URL query parameters accumulated via WithQueryParam* methods.
query url.Values
// bodyBytes is the serialised request body. Nil means no body.
bodyBytes []byte
// ctx is the context governing cancellation, deadline, and value propagation.
ctx context.Context
// timeout is the per-request deadline applied on top of ctx. When > 0,
// Execute wraps ctx with context.WithTimeout before sending.
timeout time.Duration
// pathParams holds {placeholder} → value substitutions applied to rawURL
// before the request is built.
pathParams map[string]string
// tags are client-side key/value labels attached by the caller. They are
// never sent as HTTP headers; they are visible to OnBeforeRequest and
// OnAfterResponse hooks.
tags map[string]string
// uploadProgress is called during body upload with bytes transferred / total.
uploadProgress ProgressFunc
// downloadProgress is called during body download with bytes transferred / total.
downloadProgress ProgressFunc
// idempotencyKey is the X-Idempotency-Key header value to use. When set,
// it is reused across retry attempts. Set via WithIdempotencyKey or
// auto-generated when WithAutoIdempotencyKey is configured.
idempotencyKey string
// maxBodyBytes is a per-request override for [Config.MaxResponseBodyBytes].
// Zero means use the client-level default.
maxBodyBytes int64
// pooledReader is a reference to a pooled bytes.Reader if one was created
// during build(). It must be returned to the pool after the request is sent.
pooledReader *bytes.Reader
// builtURL caches the last-built URL string to avoid rebuilding on retries
// when path/query params haven't changed. Updated when build() is called.
builtURL string
// urlDirty is set to true when path params or query params are modified,
// invalidating builtURL cache. Check before skipping URL rebuild.
urlDirty bool
// encodedQuery caches the result of r.query.Encode() to avoid re-encoding
// when only path params changed. Populated on first build; reused when
// queryDirty is false.
encodedQuery string
// queryDirty is set to true by WithQueryParam* methods and cleared after
// re-encoding. When false and encodedQuery is non-empty, the cached encoded
// query is reused without calling r.query.Encode() again.
queryDirty bool
// priority is the request's priority level for queue ordering when a
// priority queue is enabled. Defaults to PriorityNormal. Only used when
// the client has WithPriorityQueue() enabled.
priority Priority
}
// newRequest allocates a Request with all maps initialised and a background
// context. It is the single construction point; callers never create Request
// literals directly.
func newRequest(method, rawURL string) *Request {
return &Request{
method: method,
rawURL: rawURL,
ctx: context.Background(),
priority: PriorityNormal,
}
}
// initHeaders lazily allocates the headers map on first write.
func (r *Request) initHeaders() {
if r.headers == nil {
r.headers = make(map[string]string)
}
}
// initPathParams lazily allocates the pathParams map on first write.
func (r *Request) initPathParams() {
if r.pathParams == nil {
r.pathParams = make(map[string]string)
}
}
// Method returns the HTTP verb for this request (e.g. "GET", "POST").
func (r *Request) Method() string { return r.method }
// URL returns the raw URL string as provided to the builder, before path
// parameters are substituted or query parameters are appended.
func (r *Request) URL() string { return r.rawURL }
// WithContext sets the context used for this request. If the context carries a
// deadline it races with any timeout set via [Request.WithTimeout] - whichever
// fires first cancels the request.
func (r *Request) WithContext(ctx context.Context) *Request { r.ctx = ctx; return r }
// WithTimeout sets a per-request timeout that wraps the existing context.
// When the timeout fires, [Client.Execute] returns [ErrTimeout].
func (r *Request) WithTimeout(d time.Duration) *Request { r.timeout = d; return r }
// WithPriority sets the priority level for this request. When the client has
// [WithPriorityQueue] enabled and the bulkhead is at capacity, requests with
// higher priority are dequeued before lower-priority ones. When WithPriorityQueue
// is not enabled, this has no effect. Defaults to PriorityNormal.
func (r *Request) WithPriority(p Priority) *Request { r.priority = p; return r }
// Priority returns the priority level set via [Request.WithPriority].
// Returns PriorityNormal if not explicitly set.
func (r *Request) Priority() Priority { return r.priority }
// WithPathParam replaces a {key} placeholder in the URL template before
// sending. The value is percent-encoded automatically.
//
// client.Get("/users/{id}").WithPathParam("id", "usr_42")
// // → GET /users/usr_42
func (r *Request) WithPathParam(key, value string) *Request {
r.initPathParams()
r.pathParams[key] = value
r.urlDirty = true
return r
}
// WithPathParams sets multiple URL path parameters at once.
//
// client.Get("/orgs/{org}/users/{id}").WithPathParams(map[string]string{
// "org": "alicorp",
// "id": "usr_42",
// })
func (r *Request) WithPathParams(params map[string]string) *Request {
if len(params) > 0 {
r.initPathParams()
}
for k, v := range params {
r.pathParams[k] = v
}
r.urlDirty = true
return r
}
// WithTag attaches a client-side key/value label to the request.
// Tags are NOT sent as HTTP headers - they are visible to [Config.OnBeforeRequest]
// and [Config.OnAfterResponse] hooks for logging, metrics labelling, etc.
//
// req.WithTag("operation", "CreateOrder").WithTag("team", "payments")
func (r *Request) WithTag(key, value string) *Request {
if r.tags == nil {
r.tags = make(map[string]string)
}
r.tags[key] = value
return r
}
// Tag returns the value of a tag previously set via [Request.WithTag], or ""
// if the tag is absent.
func (r *Request) Tag(key string) string { return r.tags[key] }
// Tags returns a copy of all tags attached to this request. Returns nil if no
// tags have been set.
func (r *Request) Tags() map[string]string {
if len(r.tags) == 0 {
return nil
}
cp := make(map[string]string, len(r.tags))
for k, v := range r.tags {
cp[k] = v
}
return cp
}
// WithHeader sets (or replaces) a single request header. Per-request headers
// take precedence over [Config.DefaultHeaders].
// CRLF characters (\r, \n) are stripped from the value to prevent header injection.
func (r *Request) WithHeader(key, value string) *Request {
r.initHeaders()
r.headers[key] = sanitizeHeaderValue(value)
return r
}
// WithHeaders merges the given map into the request headers. Later keys in the
// map override earlier ones; per-request headers always beat defaults.
// CRLF characters (\r, \n) are stripped from values to prevent header injection.
func (r *Request) WithHeaders(headers map[string]string) *Request {
if len(headers) > 0 {
r.initHeaders()
}
for k, v := range headers {
r.headers[k] = sanitizeHeaderValue(v)
}
return r
}
// sanitizeHeaderValue removes CR (\r) and LF (\n) characters from a header
// value. net/http will reject headers containing these bytes at the transport
// layer; stripping them early produces a clear, predictable result instead of
// a cryptic transport-level error and prevents HTTP header injection attacks.
func sanitizeHeaderValue(v string) string {
if !strings.ContainsAny(v, "\r\n") {
return v
}
v = strings.ReplaceAll(v, "\r", "")
v = strings.ReplaceAll(v, "\n", "")
return v
}
// initQuery lazily allocates the query map on first write.
func (r *Request) initQuery() {
if r.query == nil {
r.query = make(url.Values)
}
}
// WithQueryParam sets (or replaces) a single URL query parameter.
func (r *Request) WithQueryParam(key, value string) *Request {
r.initQuery()
r.query.Set(key, value)
r.urlDirty = true
r.queryDirty = true
return r
}
// WithQueryParams merges the given map into the URL query string. Later keys
// override earlier ones for the same name.
func (r *Request) WithQueryParams(params map[string]string) *Request {
if len(params) > 0 {
r.initQuery()
}
for k, v := range params {
r.query.Set(k, v)
}
r.urlDirty = true
r.queryDirty = true
return r
}
// WithQueryParamValues sets a multi-value query parameter, replacing any
// previously set values for the same key.
//
// req.WithQueryParamValues("ids", []string{"1", "2", "3"})
// // → ?ids=1&ids=2&ids=3
func (r *Request) WithQueryParamValues(key string, values []string) *Request {
r.initQuery()
r.query[key] = values
r.urlDirty = true
r.queryDirty = true
return r
}
// WithBody sets the raw request body bytes. The caller is responsible for also
// setting Content-Type via [Request.WithContentType].
func (r *Request) WithBody(body []byte) *Request { r.bodyBytes = body; return r }
// WithContentType sets the Content-Type request header.
func (r *Request) WithContentType(ct string) *Request {
r.initHeaders()
r.headers["Content-Type"] = ct
return r
}
// WithAccept sets the Accept request header.
func (r *Request) WithAccept(accept string) *Request {
r.initHeaders()
r.headers["Accept"] = accept
return r
}
// WithUserAgent sets the User-Agent request header, overriding any client-level
// default set via [WithDefaultHeaders].
func (r *Request) WithUserAgent(ua string) *Request {
r.initHeaders()
r.headers["User-Agent"] = ua
return r
}
// WithRequestID sets the X-Request-Id header. Useful for distributed tracing
// and log correlation when managing request identifiers outside of OTel.
func (r *Request) WithRequestID(id string) *Request {
r.initHeaders()
r.headers["X-Request-Id"] = id
return r
}
// WithAPIKey sets a header-based API key. The header name varies by service;
// common choices are "X-API-Key" and "Authorization".
//
// req.WithAPIKey("X-API-Key", os.Getenv("SERVICE_API_KEY"))
func (r *Request) WithAPIKey(headerName, apiKey string) *Request {
r.initHeaders()
r.headers[headerName] = apiKey
return r
}
// WithBodyReader reads all bytes from reader and sets them as the request body.
// If the reader returns an error the body is left unchanged. For very large
// payloads prefer [Client.ExecuteStream] combined with a custom RoundTripper.
func (r *Request) WithBodyReader(reader io.Reader) *Request {
data, err := io.ReadAll(reader)
if err != nil {
return r
}
r.bodyBytes = data
return r
}
// WithJSON marshals v to JSON, sets the body, and sets Content-Type to
// application/json. If marshalling fails the body is left unchanged.
func (r *Request) WithJSON(v interface{}) *Request {
data, err := json.Marshal(v)
if err != nil {
return r
}
r.bodyBytes = data
r.initHeaders()
r.headers["Content-Type"] = "application/json"
return r
}
// WithFormData URL-encodes data and sets Content-Type to
// application/x-www-form-urlencoded.
func (r *Request) WithFormData(data map[string]string) *Request {
form := url.Values{}
for k, v := range data {
form.Set(k, v)
}
r.bodyBytes = []byte(form.Encode())
r.initHeaders()
r.headers["Content-Type"] = "application/x-www-form-urlencoded"
return r
}
// WithMultipart builds a multipart/form-data body from the provided fields.
// Supports plain form fields and file uploads with optional Content-Type
// overrides.
func (r *Request) WithMultipart(fields []MultipartField) *Request {
var buf bytes.Buffer
w := multipart.NewWriter(&buf)
for _, f := range fields {
// Sanitise field and file names before embedding them in MIME headers.
// CR and LF characters would allow header injection; embedded quotes
// would break the Content-Disposition quoted-string parameter.
fieldName := sanitizeMIMEParam(f.FieldName)
fileName := sanitizeMIMEParam(f.FileName)
if fileName != "" {
var part io.Writer
if f.ContentType != "" {
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition", fmt.Sprintf(
`form-data; name="%s"; filename="%s"`, fieldName, fileName,
))
h.Set("Content-Type", f.ContentType)
part, _ = w.CreatePart(h)
} else {
part, _ = w.CreateFormFile(fieldName, fileName)
}
if f.Reader != nil {
_, _ = io.Copy(part, f.Reader)
} else {
_, _ = part.Write(f.Content)
}
} else {
_ = w.WriteField(fieldName, string(f.Content))
}
}
_ = w.Close()
r.bodyBytes = buf.Bytes()
r.initHeaders()
r.headers["Content-Type"] = w.FormDataContentType()
return r
}
// sanitizeMIMEParam strips CR and LF characters (which would enable MIME
// header injection) and escapes double-quote characters so the value is safe
// to embed in a quoted Content-Disposition parameter.
func sanitizeMIMEParam(s string) string {
s = strings.ReplaceAll(s, "\r", "")
s = strings.ReplaceAll(s, "\n", "")
s = strings.ReplaceAll(s, `"`, `\"`)
return s
}
// WithBearerToken sets the Authorization header to "Bearer <token>".
func (r *Request) WithBearerToken(token string) *Request {
r.initHeaders()
r.headers["Authorization"] = "Bearer " + token
return r
}
// WithBasicAuth sets the Authorization header to the RFC 7617 Basic credential
// for the given username and password.
func (r *Request) WithBasicAuth(username, password string) *Request {
credentials := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
r.initHeaders()
r.headers["Authorization"] = "Basic " + credentials
return r
}
// WithUploadProgress registers a callback that is invoked periodically during
// request body upload. transferred is the number of bytes sent so far; total is
// the body size or -1 if unknown.
func (r *Request) WithUploadProgress(fn ProgressFunc) *Request {
r.uploadProgress = fn
return r
}
// WithDownloadProgress registers a callback that is invoked periodically during
// response body download. transferred is bytes read so far; total is Content-Length
// or -1 if the header is absent.
func (r *Request) WithDownloadProgress(fn ProgressFunc) *Request {
r.downloadProgress = fn
return r
}
// WithIdempotencyKey sets a custom X-Idempotency-Key header value. The key is
// reused unchanged across all retry attempts for this request.
// The value is sanitised to strip CR/LF characters.
func (r *Request) WithIdempotencyKey(key string) *Request {
r.idempotencyKey = sanitizeHeaderValue(key)
return r
}
// WithMaxBodySize overrides the client-level [Config.MaxResponseBodyBytes] for
// this single request. Pass 0 to fall back to the client default (10 MB).
// Pass -1 to remove the limit entirely for this request.
func (r *Request) WithMaxBodySize(n int64) *Request { r.maxBodyBytes = n; return r }
// WithDeduplication overrides the client-level deduplication setting for this
// single request. Call with no argument or true to force deduplication on;
// call with false to disable it even when the client has deduplication enabled.
func (r *Request) WithDeduplication(enabled ...bool) *Request {
e := true
if len(enabled) > 0 {
e = enabled[0]
}
r.ctx = context.WithValue(r.ctx, deduplicationOverrideKey{}, e)
return r
}
// Clone returns a deep copy of the request. All maps and slices are
// independently duplicated so mutations to the clone do not affect the
// original, and vice-versa. The body bytes slice is also copied.
//
// Clone is useful when the same base request needs to be dispatched with
// different headers, query params, or bodies without constructing from scratch.
func (r *Request) Clone() *Request {
clone := *r
if len(r.headers) > 0 {
clone.headers = make(map[string]string, len(r.headers))
for k, v := range r.headers {
clone.headers[k] = v
}
}
if len(r.query) > 0 {
clone.query = make(url.Values, len(r.query))
for k, v := range r.query {
clone.query[k] = append([]string(nil), v...)
}
}
if len(r.pathParams) > 0 {
clone.pathParams = make(map[string]string, len(r.pathParams))
for k, v := range r.pathParams {
clone.pathParams[k] = v
}
}
if r.tags != nil {
clone.tags = make(map[string]string, len(r.tags))
for k, v := range r.tags {
clone.tags[k] = v
}
}
if r.bodyBytes != nil {
clone.bodyBytes = append([]byte(nil), r.bodyBytes...)
}
// pooledReader must not be cloned - each request build creates its own
clone.pooledReader = nil
// URL cache must be invalidated for clone since params may change.
// Preserve encodedQuery so the clone can reuse it if query is unchanged.
clone.builtURL = ""
clone.urlDirty = false
return &clone
}
// withCtx returns a shallow clone of r with the context replaced. Used
// internally by [Client.Execute] when applying a per-request timeout so the
// original Request is not mutated.
func (r *Request) withCtx(ctx context.Context) *Request {
clone := *r
clone.ctx = ctx
return &clone
}
// applyPathParams substitutes every {key} placeholder in rawURL with its
// corresponding percent-encoded value from pathParams.
func (r *Request) applyPathParams(rawURL string) string {
if len(r.pathParams) == 0 {
return rawURL
}
// Build placeholders map to avoid allocating "{key}" string in each iteration.
result := rawURL
for k, v := range r.pathParams {
placeholder := "{" + k + "}"
result = strings.ReplaceAll(result, placeholder, url.PathEscape(v))
}
return result
}
// build constructs the stdlib *http.Request from this builder's state.
// It applies path params, resolves the URL against baseURL/parsedBaseURL,
// appends query params, and sets all headers. parsedBaseURL, if non-nil,
// is used as an optimization to avoid re-parsing. Built URL is cached to
// avoid rebuild on retries when params haven't changed.
//
// normalisationMode controls which URL resolution strategy is used:
// - NormalisationAuto: Intelligent detection (API vs host-only)
// - NormalisationRFC3986: Force RFC 3986 (zero-alloc, breaks APIs)
// - NormalisationAPI: Force safe normalisation (preserves paths)
func (r *Request) build(baseURL string, parsedBaseURL *url.URL, normalisationMode URLNormalisationMode) (*http.Request, error) {
// Fast path: if URL hasn't been modified and was cached, reuse it
if r.builtURL != "" && !r.urlDirty {
// Reuse cached URL for retries
var bodyReader io.Reader
if len(r.bodyBytes) > 0 {
r.pooledReader = pool.GetBytesReader(r.bodyBytes)
bodyReader = r.pooledReader
if r.uploadProgress != nil {
bodyReader = newProgressReader(bodyReader, int64(len(r.bodyBytes)), r.uploadProgress)
}
}
req, err := http.NewRequestWithContext(r.ctx, r.method, r.builtURL, bodyReader)
if err != nil {
return nil, err
}
for k, v := range r.headers {
req.Header.Set(k, v)
}
return req, nil
}
fullURL := r.applyPathParams(r.rawURL)
if baseURL != "" && !strings.HasPrefix(fullURL, "http://") && !strings.HasPrefix(fullURL, "https://") {
// Determine which normalisation strategy to use
useRFC3986 := false
switch normalisationMode {
case NormalisationAuto:
// Intelligent detection: RFC 3986 for host-only, safe for APIs
useRFC3986 = parsedBaseURL != nil && !isAPIBase(baseURL)
case NormalisationRFC3986:
// Force RFC 3986 (requires parsed URL)
useRFC3986 = parsedBaseURL != nil
case NormalisationAPI:
// Force safe normalisation
useRFC3986 = false
}
if useRFC3986 {
// Fast path: host-only base URL (with or without trailing slash) +
// absolute request path. Avoids 4 allocs from ResolveReference
// (&url.URL, internal copy, String(), plus escaping).
// AutoNormaliseBaseURL adds a trailing slash so parsedBaseURL.Path
// can be "/" even for host-only bases -- treat that identically.
isHostOnly := (parsedBaseURL.Path == "" || parsedBaseURL.Path == "/")
if isHostOnly && len(fullURL) > 0 && fullURL[0] == '/' && parsedBaseURL.User == nil {
// Normalise excess leading slashes (e.g. "//path" → "/path") to
// prevent double-slash URLs like "https://host//path" which some
// servers (SAP, nginx) reject with 401/404 instead of redirecting.
normPath := "/" + strings.TrimLeft(fullURL, "/")
fullURL = parsedBaseURL.Scheme + "://" + parsedBaseURL.Host + normPath
} else {
// Slow path: proper RFC 3986 resolution for complex base URLs.
// Split any query string out of fullURL before building the
// url.URL reference; placing '?' in the Path field causes
// url.URL.String() to percent-encode it as %3F.
pathPart := fullURL
rawQuery := ""
if idx := strings.IndexByte(fullURL, '?'); idx >= 0 {
pathPart = fullURL[:idx]
rawQuery = fullURL[idx+1:]
}
resolved := parsedBaseURL.ResolveReference(&url.URL{Path: pathPart, RawQuery: rawQuery})
fullURL = resolved.String()
}
} else {
// Path 2: Use safe string normalisation for API URLs.
// Handles API base URLs with path components (e.g., http://api.com/v1/odata)
// correctly by preserving the entire base path instead of replacing it per RFC 3986.
var sb strings.Builder
sb.Grow(len(baseURL) + len(fullURL) + 1)
// TrimRight baseURL and write
trimmedBase := strings.TrimRight(baseURL, "/")
sb.WriteString(trimmedBase)
sb.WriteByte('/')
// TrimLeft fullURL and write
trimmedPath := strings.TrimLeft(fullURL, "/")
sb.WriteString(trimmedPath)
fullURL = sb.String()
}
}
if len(r.query) > 0 {
if !strings.Contains(fullURL, "?") {
// Fast path: no existing query params - skip url.Parse and
// use cached encoded query when params haven't changed.
if r.queryDirty || r.encodedQuery == "" {
r.encodedQuery = r.query.Encode()
r.queryDirty = false
}
var sb strings.Builder
sb.Grow(len(fullURL) + 1 + len(r.encodedQuery))
sb.WriteString(fullURL)
sb.WriteByte('?')
sb.WriteString(r.encodedQuery)
fullURL = sb.String()
} else {
// Slow path: URL already contains a query string - merge.
parsed, err := url.Parse(fullURL)
if err != nil {
return nil, err
}
existing := parsed.Query()
for k, vs := range r.query {
for _, v := range vs {
existing.Add(k, v)
}
}
parsed.RawQuery = existing.Encode()
fullURL = parsed.String()
}
}
// Cache the built URL and clear dirty flag for next build
r.builtURL = fullURL
r.urlDirty = false
var bodyReader io.Reader
if len(r.bodyBytes) > 0 {
r.pooledReader = pool.GetBytesReader(r.bodyBytes)
bodyReader = r.pooledReader
if r.uploadProgress != nil {
bodyReader = newProgressReader(bodyReader, int64(len(r.bodyBytes)), r.uploadProgress)
}
}
req, err := http.NewRequestWithContext(r.ctx, r.method, fullURL, bodyReader)
if err != nil {
return nil, err
}
for k, v := range r.headers {
req.Header.Set(k, v)
}
return req, nil
}
// releasePooledReader returns the pooled bytes.Reader to the pool if one was
// created during build(). Must be called after the request has been sent.
func (r *Request) releasePooledReader() {
if r.pooledReader != nil {
pool.PutBytesReader(r.pooledReader)
r.pooledReader = nil
}
}