-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.go
More file actions
363 lines (316 loc) · 9.26 KB
/
Copy pathrequest.go
File metadata and controls
363 lines (316 loc) · 9.26 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
package rhttp
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"encoding/xml"
"io"
"net/http"
"net/url"
"strings"
"time"
)
// RequestBuilder provides a fluent interface for building HTTP requests.
//
// A builder is meant for a single request and is not safe for concurrent use.
// Bodies set from bytes (SetBodyBytes, SetBodyString, SetBodyJSON, SetBodyXML,
// SetBodyForm) survive re-execution; a body set from a reader via SetBody is
// consumed by the first execution.
type RequestBuilder struct {
client *Client
ctx context.Context
method string
url string
headers http.Header
queryParams url.Values
pathParams map[string]string
body io.Reader
bodyBytes []byte
timeout time.Duration
err error
}
// R creates a new RequestBuilder bound to the client.
// Query and path parameter maps are initialized lazily on first use.
func (c *Client) R() *RequestBuilder {
return &RequestBuilder{
client: c,
ctx: context.Background(),
headers: make(http.Header),
}
}
// Context sets the context for the request.
func (rb *RequestBuilder) Context(ctx context.Context) *RequestBuilder {
rb.ctx = ctx
return rb
}
// SetTimeout sets a timeout for this specific request.
func (rb *RequestBuilder) SetTimeout(d time.Duration) *RequestBuilder {
rb.timeout = d
return rb
}
// SetHeader sets a single header.
func (rb *RequestBuilder) SetHeader(key, value string) *RequestBuilder {
rb.headers.Set(key, value)
return rb
}
// SetHeaders sets multiple headers from a map.
func (rb *RequestBuilder) SetHeaders(headers map[string]string) *RequestBuilder {
for k, v := range headers {
rb.headers.Set(k, v)
}
return rb
}
// AddHeader adds a header value (allows multiple values for same key).
func (rb *RequestBuilder) AddHeader(key, value string) *RequestBuilder {
rb.headers.Add(key, value)
return rb
}
// SetContentType sets the Content-Type header.
func (rb *RequestBuilder) SetContentType(contentType string) *RequestBuilder {
return rb.SetHeader("Content-Type", contentType)
}
// SetAccept sets the Accept header.
func (rb *RequestBuilder) SetAccept(accept string) *RequestBuilder {
return rb.SetHeader("Accept", accept)
}
// SetUserAgent sets the User-Agent header.
func (rb *RequestBuilder) SetUserAgent(ua string) *RequestBuilder {
return rb.SetHeader("User-Agent", ua)
}
// SetAuthToken sets a Bearer token in the Authorization header.
func (rb *RequestBuilder) SetAuthToken(token string) *RequestBuilder {
return rb.SetHeader("Authorization", "Bearer "+token)
}
// SetBasicAuth sets Basic authentication.
func (rb *RequestBuilder) SetBasicAuth(username, password string) *RequestBuilder {
rb.headers.Set("Authorization", "Basic "+basicAuth(username, password))
return rb
}
func (rb *RequestBuilder) ensureQueryParams() {
if rb.queryParams == nil {
rb.queryParams = make(url.Values)
}
}
// SetQueryParam sets a single query parameter.
func (rb *RequestBuilder) SetQueryParam(key, value string) *RequestBuilder {
rb.ensureQueryParams()
rb.queryParams.Set(key, value)
return rb
}
// SetQueryParams sets multiple query parameters from a map.
func (rb *RequestBuilder) SetQueryParams(params map[string]string) *RequestBuilder {
rb.ensureQueryParams()
for k, v := range params {
rb.queryParams.Set(k, v)
}
return rb
}
// AddQueryParam adds a query parameter (allows multiple values for same key).
func (rb *RequestBuilder) AddQueryParam(key, value string) *RequestBuilder {
rb.ensureQueryParams()
rb.queryParams.Add(key, value)
return rb
}
func (rb *RequestBuilder) ensurePathParams() {
if rb.pathParams == nil {
rb.pathParams = make(map[string]string)
}
}
// SetPathParam sets a path parameter to be replaced in the URL.
// Example: SetPathParam("id", "123") replaces {id} in "/users/{id}".
func (rb *RequestBuilder) SetPathParam(key, value string) *RequestBuilder {
rb.ensurePathParams()
rb.pathParams[key] = value
return rb
}
// SetPathParams sets multiple path parameters from a map.
func (rb *RequestBuilder) SetPathParams(params map[string]string) *RequestBuilder {
rb.ensurePathParams()
for k, v := range params {
rb.pathParams[k] = v
}
return rb
}
// SetBody sets the request body from a reader.
//
// The reader is buffered up to 10 MB so the body can be rewound and the request
// retried. If the body exceeds 10 MB it is streamed instead: the request is sent
// once and is not retried, since the reader cannot be replayed.
func (rb *RequestBuilder) SetBody(body io.Reader) *RequestBuilder {
rb.body = body
return rb
}
// SetBodyBytes sets the request body from bytes.
func (rb *RequestBuilder) SetBodyBytes(body []byte) *RequestBuilder {
rb.bodyBytes = body
rb.body = bytes.NewReader(body)
return rb
}
// SetBodyString sets the request body from a string.
func (rb *RequestBuilder) SetBodyString(body string) *RequestBuilder {
return rb.SetBodyBytes([]byte(body))
}
// SetBodyJSON marshals the value to JSON and sets it as the body.
func (rb *RequestBuilder) SetBodyJSON(v any) *RequestBuilder {
data, err := json.Marshal(v)
if err != nil {
rb.err = err
return rb
}
rb.SetContentType("application/json")
return rb.SetBodyBytes(data)
}
// SetBodyXML marshals the value to XML and sets it as the body.
func (rb *RequestBuilder) SetBodyXML(v any) *RequestBuilder {
data, err := xml.Marshal(v)
if err != nil {
rb.err = err
return rb
}
rb.SetContentType("application/xml")
return rb.SetBodyBytes(data)
}
// SetBodyForm sets form data as the body.
func (rb *RequestBuilder) SetBodyForm(data map[string]string) *RequestBuilder {
form := url.Values{}
for k, v := range data {
form.Set(k, v)
}
rb.SetContentType("application/x-www-form-urlencoded")
return rb.SetBodyString(form.Encode())
}
// Get executes a GET request.
func (rb *RequestBuilder) Get(url string) (*http.Response, error) {
rb.method = http.MethodGet
rb.url = url
return rb.execute()
}
// Post executes a POST request.
func (rb *RequestBuilder) Post(url string) (*http.Response, error) {
rb.method = http.MethodPost
rb.url = url
return rb.execute()
}
// Put executes a PUT request.
func (rb *RequestBuilder) Put(url string) (*http.Response, error) {
rb.method = http.MethodPut
rb.url = url
return rb.execute()
}
// Patch executes a PATCH request.
func (rb *RequestBuilder) Patch(url string) (*http.Response, error) {
rb.method = http.MethodPatch
rb.url = url
return rb.execute()
}
// Delete executes a DELETE request.
func (rb *RequestBuilder) Delete(url string) (*http.Response, error) {
rb.method = http.MethodDelete
rb.url = url
return rb.execute()
}
// Head executes a HEAD request.
func (rb *RequestBuilder) Head(url string) (*http.Response, error) {
rb.method = http.MethodHead
rb.url = url
return rb.execute()
}
// Options executes an OPTIONS request.
func (rb *RequestBuilder) Options(url string) (*http.Response, error) {
rb.method = http.MethodOptions
rb.url = url
return rb.execute()
}
// Execute executes the request with the configured method.
func (rb *RequestBuilder) Execute(method, url string) (*http.Response, error) {
rb.method = method
rb.url = url
return rb.execute()
}
const maxBufferBytes = 10 << 20
func bufferBody(r io.Reader) ([]byte, io.Reader, error) {
buf, err := io.ReadAll(io.LimitReader(r, maxBufferBytes+1))
if err != nil {
return nil, nil, err
}
if len(buf) > maxBufferBytes {
return nil, io.MultiReader(bytes.NewReader(buf), r), nil
}
return buf, nil, nil
}
func (rb *RequestBuilder) resolveBody() (io.Reader, []byte, error) {
if rb.body == nil {
return nil, rb.bodyBytes, nil
}
if rb.bodyBytes != nil {
return bytes.NewReader(rb.bodyBytes), rb.bodyBytes, nil
}
buf, stream, err := bufferBody(rb.body)
if err != nil {
return nil, nil, err
}
if stream != nil {
return stream, nil, nil
}
return bytes.NewReader(buf), buf, nil
}
func (rb *RequestBuilder) execute() (*http.Response, error) {
if rb.err != nil {
return nil, rb.err
}
// Apply path parameters
finalURL := rb.url
for k, v := range rb.pathParams {
finalURL = strings.ReplaceAll(finalURL, "{"+k+"}", url.PathEscape(v))
}
// Apply query parameters
if len(rb.queryParams) > 0 {
if strings.Contains(finalURL, "?") {
finalURL += "&" + rb.queryParams.Encode()
} else {
finalURL += "?" + rb.queryParams.Encode()
}
}
// Create body reader
bodyReader, bodyBytes, err := rb.resolveBody()
if err != nil {
return nil, err
}
// Create request
req, err := http.NewRequest(rb.method, finalURL, bodyReader)
if err != nil {
return nil, err
}
// Set GetBody for retry support
if bodyBytes != nil {
req.GetBody = func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(bodyBytes)), nil
}
req.ContentLength = int64(len(bodyBytes))
}
// Client.Do clones the request, so sharing the builder's header map is safe.
req.Header = rb.headers
// Apply timeout
ctx := rb.ctx
if rb.timeout <= 0 {
return rb.client.Do(ctx, req)
}
ctx, cancel := context.WithTimeout(ctx, rb.timeout)
resp, err := rb.client.Do(ctx, req)
if err != nil {
cancel()
return resp, err
}
if resp.Body == nil {
cancel()
return resp, nil
}
resp.Body = &cancelBody{ReadCloser: resp.Body, cancel: cancel}
return resp, nil
}
// basicAuth encodes username and password for Basic authentication.
func basicAuth(username, password string) string {
auth := username + ":" + password
return base64.StdEncoding.EncodeToString([]byte(auth))
}