-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoptions.go
More file actions
361 lines (332 loc) · 7.85 KB
/
options.go
File metadata and controls
361 lines (332 loc) · 7.85 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
package requests
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"os"
"time"
"github.com/Wenchy/requests/internal/auth"
)
// Options defines all optional parameters for HTTP request.
type Options struct {
ctx context.Context
Headers http.Header
Params url.Values
// body
bodyType bodyType
Body io.Reader
// different request body types
Data any
Form url.Values
JSON any
Files map[string]*os.File
// different response body types
ToText *string
ToJSON any
// auth
AuthInfo *auth.AuthInfo
// request timeout
Timeout time.Duration
// dump
DumpRequestOut *string
DumpResponse *string
// interceptor
Interceptor InterceptorFunc
}
// Option is the functional option type.
type Option func(*Options)
// newDefaultOptions creates a new default HTTP options.
func newDefaultOptions() *Options {
return &Options{
ctx: context.Background(),
Headers: http.Header{},
bodyType: bodyTypeDefault,
}
}
func parseOptions(options ...Option) *Options {
opts := newDefaultOptions()
for _, setter := range options {
setter(opts)
}
return opts
}
// Context sets the HTTP request context.
//
// For outgoing client request, the context controls the entire lifetime of
// a request and its response: obtaining a connection, sending the request,
// and reading the response headers and body.
func Context(ctx context.Context) Option {
return func(opts *Options) {
opts.ctx = ctx
}
}
// Headers sets the HTTP headers. The keys should be in canonical form, as
// returned by [http.CanonicalHeaderKey]. Two types are supported:
//
// # Type 1: map[string]string
//
// map[string]string(
// "Header-Key1", "val1",
// "Header-Key2", "val2",
// )
//
// # Type 2: http.Header
//
// http.Header(
// "Header-Key1", []string{"val1", "val1-2"},
// "Header-Key2", "val2",
// )
//
// [http.CanonicalHeaderKey]: https://pkg.go.dev/net/http#CanonicalHeaderKey
func Headers[T map[string]string | http.Header](headers T) Option {
return func(opts *Options) {
switch headers := any(headers).(type) {
case map[string]string:
for k, v := range headers {
opts.Headers.Add(k, v)
}
case http.Header:
for key, values := range headers {
for _, value := range values {
opts.Headers.Add(key, value)
}
}
}
}
}
// HeaderPairs sets HTTP headers formed by the mapping of key-value pairs.
// The keys should be in canonical form, as returned by
// [http.CanonicalHeaderKey]. It panics if len(kv) is odd.
//
// Values with the same key will be merged into a list:
//
// HeaderPairs(
// "Key1", "val1",
// "Key1", "val1-2", // "Key1" will have map value []string{"val1", "val1-2"}
// "Key2", "val2",
// )
//
// [http.CanonicalHeaderKey]: https://pkg.go.dev/net/http#CanonicalHeaderKey
func HeaderPairs(kv ...string) Option {
if len(kv)%2 == 1 {
panic(fmt.Sprintf("params: got the odd number of input pairs: %d", len(kv)))
}
headers := http.Header{}
var key string
for i, s := range kv {
if i%2 == 0 {
key = s
continue
}
headers.Add(key, s)
}
return Headers(headers)
}
// Params sets the given query parameters into the URL query string.
// Two types are supported:
//
// # Type 1: map[string]string
//
// map[string]string(
// "key1", "val1",
// "key2", "val2",
// )
//
// # Type 2: url.Values
//
// url.Values(
// "key1", []string{"val1", "val1-2"},
// "key2", "val2",
// )
func Params[T map[string]string | url.Values](params T) Option {
return func(opts *Options) {
if opts.Params == nil {
opts.Params = url.Values{}
}
switch params := any(params).(type) {
case map[string]string:
for k, v := range params {
opts.Params.Add(k, v)
}
case url.Values:
for key, values := range params {
for _, value := range values {
opts.Params.Add(key, value)
}
}
}
}
}
// ParamPairs sets the query parameters formed by the mapping of key-value pairs.
// It panics if len(kv) is odd.
//
// Values with the same key will be merged into a list:
//
// ParamPairs(
// "key1", "val1",
// "key1", "val1-2", // "key1" will have map value []string{"val1", "val1-2"}
// "key2", "val2",
// )
func ParamPairs(kv ...string) Option {
if len(kv)%2 == 1 {
panic(fmt.Sprintf("params: got the odd number of input pairs: %d", len(kv)))
}
params := url.Values{}
var key string
for i, s := range kv {
if i%2 == 0 {
key = s
continue
}
params.Add(key, s)
}
return Params(params)
}
// Body sets io.Reader to hold request body.
func Body(body io.Reader) Option {
return func(opts *Options) {
opts.Body = body
opts.bodyType = bodyTypeDefault
}
}
// Data sets raw string into the request body.
func Data(data any) Option {
return func(opts *Options) {
opts.Data = data
opts.bodyType = bodyTypeData
}
}
// Form sets the given form values into the request body.
// It also sets the Content-Type as "application/x-www-form-urlencoded".
// Two types are supported:
//
// # Type 1: map[string]string
//
// map[string]string(
// "key1", "val1",
// "key2", "val2",
// )
//
// # Type 2: url.Values
//
// url.Values(
// "key1", []string{"val1", "val1-2"},
// "key2", "val2",
// )
func Form[T map[string]string | url.Values](params T) Option {
return func(opts *Options) {
if opts.Form == nil {
opts.Form = url.Values{}
}
switch params := any(params).(type) {
case map[string]string:
for k, v := range params {
opts.Form.Add(k, v)
}
case url.Values:
for key, values := range params {
for _, value := range values {
opts.Form.Add(key, value)
}
}
}
opts.bodyType = bodyTypeForm
}
}
// FormPairs sets form values by the mapping of key-value pairs.
// It panics if len(kv) is odd.
//
// Values with the same key will be merged into a list:
//
// FormPairs(
// "key1", "val1",
// "key1", "val1-2", // "key1" will have map value []string{"val1", "val1-2"}
// "key2", "val2",
// )
func FormPairs(kv ...string) Option {
if len(kv)%2 == 1 {
panic(fmt.Sprintf("params: got the odd number of input pairs: %d", len(kv)))
}
form := url.Values{}
var key string
for i, s := range kv {
if i%2 == 0 {
key = s
continue
}
form.Add(key, s)
}
return Form(form)
}
// JSON marshals the given struct as JSON into the request body.
// It also sets the Content-Type as "application/json".
func JSON(v any) Option {
return func(opts *Options) {
opts.JSON = v
opts.bodyType = bodyTypeJSON
}
}
// Files sets files to a map of (field, fileHandler).
// It also sets the Content-Type as "multipart/form-data".
func Files(files map[string]*os.File) Option {
return func(opts *Options) {
if opts.Files != nil {
for k, v := range files {
opts.Files[k] = v
}
} else {
opts.Files = files
}
opts.bodyType = bodyTypeFiles
}
}
// ToText unmarshals HTTP response body to string.
func ToText(v *string) Option {
return func(opts *Options) {
opts.ToText = v
}
}
// ToJSON unmarshals HTTP response body to given struct as JSON.
func ToJSON(v any) Option {
return func(opts *Options) {
opts.ToJSON = v
}
}
// BasicAuth is the option to implement HTTP Basic Auth.
func BasicAuth(username, password string) Option {
return func(opts *Options) {
opts.AuthInfo = &auth.AuthInfo{
Type: auth.BasicAuth,
Username: username,
Password: password,
}
}
}
// Timeout creates a new context with specified timeout for
// the current request.
func Timeout(timeout time.Duration) Option {
return func(opts *Options) {
opts.Timeout = timeout
}
}
// Dump dumps outgoing client request and response to the corresponding
// input param (req or resp) if not nil.
//
// Refer:
// - https://pkg.go.dev/net/http/httputil#DumpRequestOut
// - https://pkg.go.dev/net/http/httputil#DumpResponse
func Dump(req, resp *string) Option {
return func(opts *Options) {
opts.DumpRequestOut = req
opts.DumpResponse = resp
}
}
// Interceptor prepends an interceptor to environment interceptors for current
// request only.
func Interceptor(interceptor InterceptorFunc) Option {
return func(opts *Options) {
opts.Interceptor = interceptor
}
}