-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder.go
470 lines (401 loc) · 11.3 KB
/
builder.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
package greq
import (
"bytes"
"io"
"net/http"
gourl "net/url"
"os"
"strings"
"github.com/gookit/goutil/basefn"
"github.com/gookit/goutil/fsutil"
"github.com/gookit/goutil/netutil/httpctype"
"github.com/gookit/goutil/netutil/httpheader"
"github.com/gookit/goutil/netutil/httpreq"
"github.com/gookit/goutil/strutil"
)
const (
HeaderUAgent = "User-Agent"
HeaderAuth = "Authorization"
AgentCURL = "CURL/7.64.1 greq/1.0.2"
)
// Builder is a http request builder.
type Builder struct {
*Options
// client for send request. if not set, will use default client.
cli *Client
}
// NewBuilder for request
func NewBuilder(fns ...OptionFn) *Builder {
opt := &Options{
// Method: http.MethodGet,
Header: make(http.Header),
HeaderM: make(map[string]string),
Query: make(gourl.Values),
}
for _, fn := range fns {
fn(opt)
}
return &Builder{Options: opt}
}
// BuilderWithClient create a new builder with client
func BuilderWithClient(c *Client, optFns ...OptionFn) *Builder {
return NewBuilder(optFns...).WithClient(c)
}
func newBuilder(c *Client, method, pathURL string) *Builder {
b := NewBuilder()
b.cli = c
b.Method = method
b.pathURL = pathURL
return b
}
// WithClient set cli to builder
func (b *Builder) WithClient(c *Client) *Builder {
b.cli = c
return b
}
// WithOptionFn set option fns to builder
func (b *Builder) WithOptionFn(fns ...OptionFn) *Builder {
return b.WithOptionFns(fns)
}
// WithOptionFns set option fns to builder
func (b *Builder) WithOptionFns(fns []OptionFn) *Builder {
for _, fn := range fns {
fn(b.Options)
}
return b
}
// WithMethod set request method name.
func (b *Builder) WithMethod(method string) *Builder {
b.Method = method
return b
}
// PathURL set path URL for current request
func (b *Builder) PathURL(pathURL string) *Builder {
b.pathURL = pathURL
return b
}
//
//
// ----------- URL, Query params ------------
//
//
// AddQuery appends new k-v param to the Query string.
func (b *Builder) AddQuery(key string, value any) *Builder {
b.Query.Add(key, strutil.SafeString(value))
return b
}
// QueryParams appends url.Values/map[string]string to the Query string.
// The value will be encoded as url Query parameters on send requests (see Send()).
func (b *Builder) QueryParams(ps any) *Builder {
if ps != nil {
for key, values := range httpreq.ToQueryValues(ps) {
for _, value := range values {
b.Query.Add(key, value)
}
}
}
return b
}
// QueryValues appends url.Values to the Query string.
// The value will be encoded as url Query parameters on new requests (see Send()).
func (b *Builder) QueryValues(values gourl.Values) *Builder {
return b.QueryParams(values)
}
// WithQuerySMap appends map[string]string to the Query string.
func (b *Builder) WithQuerySMap(smp map[string]string) *Builder {
return b.QueryParams(smp)
}
//
//
// ----------- HeaderM ------------
//
//
// AddHeader adds the key, value pair in HeaderM, appending values for existing keys
// to the key's values. Header keys are canonicalized.
func (b *Builder) AddHeader(key, value string) *Builder {
b.Header.Add(key, value)
return b
}
// SetHeader sets the key, value pair in HeaderM, replacing existing values
// associated with key. Header keys are canonicalized.
func (b *Builder) SetHeader(key, value string) *Builder {
b.Header.Set(key, value)
return b
}
// AddHeaders adds all the http.Header values, appending values for existing keys
// to the key's values. Header keys are canonicalized.
func (b *Builder) AddHeaders(headers http.Header) *Builder {
for key, values := range headers {
for i := range values {
b.Header.Add(key, values[i])
}
}
return b
}
// AddHeaderMap sets all the http.Header values, appending values for existing keys
// to the key's values.
func (b *Builder) AddHeaderMap(headers map[string]string) *Builder {
for key, value := range headers {
b.Header.Add(key, value)
}
return b
}
// SetHeaders sets all the http.Header values, replacing values for existing keys
// to the key's values. Header keys are canonicalized.
func (b *Builder) SetHeaders(headers http.Header) *Builder {
for key, values := range headers {
for i := range values {
if i == 0 {
b.Header.Set(key, values[i])
} else {
b.Header.Add(key, values[i])
}
}
}
return b
}
// SetHeaderMap sets all the http.Header values, replacing values for existing keys
// to the key's values.
func (b *Builder) SetHeaderMap(headers map[string]string) *Builder {
for key, value := range headers {
b.Header.Set(key, value)
}
return b
}
// UserAgent set User-Agent header
func (b *Builder) UserAgent(ua string) *Builder {
b.HeaderM[httpheader.UserAgent] = ua
return b
}
// UserAuth with user auth header value.
func (b *Builder) UserAuth(value string) *Builder {
return b.SetHeader(httpheader.UserAuth, value)
}
// BasicAuth sets the Authorization header to use HTTP Basic Authentication
// with the provided username and password.
//
// With HTTP Basic Authentication the provided username and password are not encrypted.
func (b *Builder) BasicAuth(username, password string) *Builder {
return b.SetHeader(httpheader.UserAuth, httpreq.BuildBasicAuth(username, password))
}
//
//
// ----------- Cookies ------------
//
//
// WithCookies to request
func (b *Builder) WithCookies(hcs ...*http.Cookie) *Builder {
var sb strings.Builder
for i, hc := range hcs {
if i > 0 {
sb.WriteByte(';')
}
sb.WriteString(hc.String())
}
return b.WithCookieString(sb.String())
}
// WithCookieString set cookie header value.
//
// Usage:
//
// h.NewOpt().
// WithCookieString("name=inhere;age=30").
// Do("/some/api", "GET")
func (b *Builder) WithCookieString(value string) *Builder {
// return h.AddHeader("Set-Cookie", value) // response
return b.AddHeader("Cookie", value)
}
//
//
// ----------- Content Type ------------
//
//
// WithContentType with custom ContentType header
func (b *Builder) WithContentType(value string) *Builder {
b.ContentType = value
return b
}
// WithType with custom ContentType header
func (b *Builder) WithType(value string) *Builder {
b.ContentType = value
return b
}
// XMLType with xml Content-Type header
func (b *Builder) XMLType() *Builder {
b.ContentType = httpctype.XML
return b
}
// JSONType with json Content-Type header
func (b *Builder) JSONType() *Builder {
b.ContentType = httpctype.JSON
return b
}
// FormType with from Content-Type header
func (b *Builder) FormType() *Builder {
b.ContentType = httpctype.Form
return b
}
// MultipartType with multipart/form-data Content-Type header
func (b *Builder) MultipartType() *Builder {
b.ContentType = httpctype.FormData
return b
}
//
//
// ----------- Request Body ------------
//
//
// WithBody with custom any type body
func (b *Builder) WithBody(body any) *Builder {
return b.AnyBody(body)
}
// AnyBody with custom any type body
func (b *Builder) AnyBody(body any) *Builder {
if bp, ok := body.(BodyProvider); ok {
return b.BodyProvider(bp)
}
b.Body = body
return b
}
// BodyProvider with custom body provider
func (b *Builder) BodyProvider(bp BodyProvider) *Builder {
b.Provider = bp
return b
}
// BodyReader with custom io reader body
func (b *Builder) BodyReader(r io.Reader) *Builder {
b.Provider = bodyProvider{body: r}
return b
}
// FileContentsBody read file contents as body
func (b *Builder) FileContentsBody(filePath string) *Builder {
file, err := os.OpenFile(filePath, os.O_RDONLY, fsutil.DefaultFilePerm)
if err != nil {
panic(err)
}
return b.BodyReader(file)
}
// JSONBody with JSON data body
func (b *Builder) JSONBody(jsonData any) *Builder {
b.Provider = jsonBodyProvider{
payload: jsonData,
}
return b
}
// FormBody with form data body
func (b *Builder) FormBody(formData any) *Builder {
b.Provider = formBodyProvider{
payload: formData,
}
return b
}
// BytesBody with custom string body
func (b *Builder) BytesBody(bs []byte) *Builder {
return b.BodyReader(bytes.NewReader(bs))
}
// StringBody with custom string body
func (b *Builder) StringBody(s string) *Builder {
return b.BodyReader(strings.NewReader(s))
}
// Multipart with custom multipart body
func (b *Builder) Multipart(key, value string) *Builder {
// TODO
return b
}
//
//
// ----------- Build Request ------------
//
//
// Build request
func (b *Builder) Build(method, pathURL string) (*http.Request, error) {
b.Method = method
cli := basefn.OrValue(b.cli == nil, std, b.cli)
return cli.NewRequestWithOptions(pathURL, b.Options)
}
// String request to string.
func (b *Builder) String() string {
r, err := b.Build(b.Method, b.pathURL)
if err != nil {
return ""
}
return httpreq.RequestToString(r)
}
//
//
// ----------- Send Request ------------
//
//
// Get sets the method to GET and sets the given pathURL
func (b *Builder) Get(pathURL string, optFns ...OptionFn) *Builder {
b.pathURL = pathURL
b.Method = http.MethodGet
b.WithOptionFns(optFns)
return b
}
// GetDo sets the method to GET and sets the given pathURL,
// then send request and return response.
func (b *Builder) GetDo(pathURL string, optFns ...OptionFn) (*Response, error) {
return b.Send(http.MethodGet, pathURL, optFns...)
}
// Post sets the method to POST and sets the given pathURL
func (b *Builder) Post(pathURL string, data any, optFns ...OptionFn) *Builder {
b.pathURL = pathURL
b.Method = http.MethodPost
b.Body = data
b.WithOptionFns(optFns)
return b
}
// PostDo sets the method to POST and sets the given pathURL,
// then send request and return http response.
func (b *Builder) PostDo(pathURL string, data any, optFns ...OptionFn) (*Response, error) {
return b.Post(pathURL, data, optFns...).Do()
}
// Put sets the method to PUT and sets the given pathURL
func (b *Builder) Put(pathURL string, data any, optFns ...OptionFn) *Builder {
b.Body = data
b.pathURL = pathURL
b.Method = http.MethodPut
b.WithOptionFns(optFns)
return b
}
// PutDo sets the method to PUT and sets the given pathURL, then send request and return response.
func (b *Builder) PutDo(pathURL string, data any, optFns ...OptionFn) (*Response, error) {
return b.Put(pathURL, data, optFns...).Do()
}
// Patch sets the method to PATCH and sets the given pathURL
func (b *Builder) Patch(pathURL string, data any, optFns ...OptionFn) *Builder {
b.Body = data
b.pathURL = pathURL
b.Method = http.MethodPatch
b.WithOptionFns(optFns)
return b
}
// PatchDo sets the method to PATCH and sets the given pathURL, then send request and return response.
func (b *Builder) PatchDo(pathURL string, data any, optFns ...OptionFn) (*Response, error) {
return b.Patch(pathURL, data, optFns...).Do()
}
// Delete sets the method to DELETE and sets the given pathURL
func (b *Builder) Delete(pathURL string, optFns ...OptionFn) *Builder {
b.pathURL = pathURL
b.Method = http.MethodDelete
b.WithOptionFns(optFns)
return b
}
// DeleteDo sets the method to DELETE and sets the given pathURL, then send request and return response.
func (b *Builder) DeleteDo(pathURL string, optFns ...OptionFn) (*Response, error) {
return b.Send(http.MethodDelete, pathURL, optFns...)
}
// Do send request and return response.
func (b *Builder) Do(optFns ...OptionFn) (*Response, error) {
return b.Send(b.Method, b.pathURL, optFns...)
}
// Send request and return response, alias of Do()
func (b *Builder) Send(method, url string, optFns ...OptionFn) (*Response, error) {
if len(optFns) > 0 {
b.WithOptionFns(optFns)
}
b.Method = method
cli := basefn.OrValue(b.cli == nil, std, b.cli)
return cli.SendWithOpt(url, b.Options)
}