-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclient.go
More file actions
598 lines (561 loc) · 15.4 KB
/
Copy pathclient.go
File metadata and controls
598 lines (561 loc) · 15.4 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
package httpx
import (
"context"
"fmt"
"os"
"sync"
"time"
"github.com/imroc/req/v3"
)
const defaultTimeout = 10 * time.Second
const defaultUserAgent = "httpx (https://github.com/goforj/httpx)"
var (
defaultClient *Client
defaultOnce sync.Once
)
// Client wraps a req client with typed helpers and defaults.
// @group Client
type Client struct {
req *req.Client
errorMapper ErrorMapperFunc
}
// New creates a client with opinionated defaults and optional overrides.
// @group Client
//
// Example: configure all client options
//
// var buf bytes.Buffer
// _ = httpx.New(httpx.
// BaseURL("https://httpbin.org").
// Timeout(5*time.Second).
// Header("X-Trace", "1").
// Header("Accept", "application/json").
// Transport(http.RoundTripper(http.DefaultTransport)).
// Middleware(func(_ *req.Client, r *req.Request) error {
// r.SetHeader("X-Middleware", "1")
// return nil
// }).
// ErrorMapper(func(resp *req.Response) error {
// return fmt.Errorf("status %d", resp.StatusCode)
// }).
// DumpAll().
// DumpEachRequest().
// DumpEachRequestTo(&buf).
// Retry(func(rc *req.Client) {
// rc.SetCommonRetryCount(2)
// }).
// RetryCount(2).
// RetryFixedInterval(200*time.Millisecond).
// RetryBackoff(100*time.Millisecond, 2*time.Second).
// RetryInterval(func(_ *req.Response, attempt int) time.Duration {
// return time.Duration(attempt) * 100 * time.Millisecond
// }).
// RetryCondition(func(resp *req.Response, _ error) bool {
// return resp != nil && resp.StatusCode == 503
// }).
// RetryHook(func(_ *req.Response, _ error) {}),
// )
func New(opts ...Option) *Client {
c := &Client{
req: req.C().SetTimeout(defaultTimeout).SetUserAgent(defaultUserAgent),
}
for _, opt := range opts {
if opt == nil {
continue
}
opt.applyClient(c)
}
if _, ok := os.LookupEnv("HTTP_TRACE"); ok {
c.req.EnableDumpAll()
}
return c
}
// Default returns the shared default client.
// @group Client
func Default() *Client {
defaultOnce.Do(func() {
defaultClient = New()
})
return defaultClient
}
// Req returns the underlying req client for advanced usage.
// @group Client
func (c *Client) Req() *req.Client {
return c.req
}
// Raw returns the underlying req client for chaining raw requests.
// @group Client
func (c *Client) Raw() *req.Client {
return c.req
}
func (c *Client) clone() *Client {
if c == nil {
return New()
}
return &Client{
req: c.req.Clone(),
errorMapper: c.errorMapper,
}
}
// Get issues a GET request using the provided client.
// It remains available for compatibility; new code can use Client.Get.
// @group Requests
//
// Example: bind to a struct
//
// type GetResponse struct {
// URL string `json:"url"`
// }
//
// c := httpx.New()
// res, _ := httpx.Get[GetResponse](c, "https://httpbin.org/get")
// httpx.Dump(res)
// // #GetResponse {
// // URL => "https://httpbin.org/get" #string
// // }
//
// Example: bind to a string body
//
// resString, _ := httpx.Get[string](c, "https://httpbin.org/uuid")
// println(resString) // dumps string
// // {
// // "uuid": "becbda6d-9950-4966-ae23-0369617ba065"
// // }
func Get[T any](client *Client, url string, opts ...Option) (T, error) {
body, _, err := do[T](client, nil, methodGet, url, nil, opts)
return body, err
}
// Post issues a POST request using the provided client.
// It remains available for compatibility; new code can use Client.Post.
// @group Requests
//
// Example: typed POST
//
// type CreateUser struct {
// Name string `json:"name"`
// }
// type CreateUserResponse struct {
// JSON CreateUser `json:"json"`
// }
//
// c := httpx.New()
// res, err := httpx.Post[CreateUser, CreateUserResponse](c, "https://httpbin.org/post", CreateUser{Name: "Ana"})
// if err != nil {
// return
// }
// httpx.Dump(res) // dumps CreateUserResponse
// // #CreateUserResponse {
// // JSON => #CreateUser {
// // Name => "Ana" #string
// // }
// // }
func Post[In any, Out any](client *Client, url string, body In, opts ...Option) (Out, error) {
out, _, err := do[Out](client, nil, methodPost, url, body, opts)
return out, err
}
// Put issues a PUT request using the provided client.
// It remains available for compatibility; new code can use Client.Put.
// @group Requests
//
// Example: typed PUT
//
// type UpdateUser struct {
// Name string `json:"name"`
// }
// type UpdateUserResponse struct {
// JSON UpdateUser `json:"json"`
// }
//
// c := httpx.New()
// res, err := httpx.Put[UpdateUser, UpdateUserResponse](c, "https://httpbin.org/put", UpdateUser{Name: "Ana"})
// if err != nil {
// return
// }
// httpx.Dump(res) // dumps UpdateUserResponse
// // #UpdateUserResponse {
// // JSON => #UpdateUser {
// // Name => "Ana" #string
// // }
// // }
func Put[In any, Out any](client *Client, url string, body In, opts ...Option) (Out, error) {
out, _, err := do[Out](client, nil, methodPut, url, body, opts)
return out, err
}
// Patch issues a PATCH request using the provided client.
// It remains available for compatibility; new code can use Client.Patch.
// @group Requests
//
// Example: typed PATCH
//
// type UpdateUser struct {
// Name string `json:"name"`
// }
// type UpdateUserResponse struct {
// JSON UpdateUser `json:"json"`
// }
//
// c := httpx.New()
// res, err := httpx.Patch[UpdateUser, UpdateUserResponse](c, "https://httpbin.org/patch", UpdateUser{Name: "Ana"})
// if err != nil {
// return
// }
// httpx.Dump(res) // dumps UpdateUserResponse
// // #UpdateUserResponse {
// // JSON => #UpdateUser {
// // Name => "Ana" #string
// // }
// // }
func Patch[In any, Out any](client *Client, url string, body In, opts ...Option) (Out, error) {
out, _, err := do[Out](client, nil, methodPatch, url, body, opts)
return out, err
}
// Delete issues a DELETE request using the provided client.
// It remains available for compatibility; new code can use Client.Delete.
// @group Requests
//
// Example: typed DELETE
//
// type DeleteResponse struct {
// URL string `json:"url"`
// }
//
// c := httpx.New()
// res, err := httpx.Delete[DeleteResponse](c, "https://httpbin.org/delete")
// if err != nil {
// return
// }
// httpx.Dump(res) // dumps DeleteResponse
// // #DeleteResponse {
// // URL => "https://httpbin.org/delete" #string
// // }
func Delete[T any](client *Client, url string, opts ...Option) (T, error) {
body, _, err := do[T](client, nil, methodDelete, url, nil, opts)
return body, err
}
// Head issues a HEAD request using the provided client.
// It remains available for compatibility; new code can use Client.Head.
// @group Requests
//
// Example: HEAD request
//
// c := httpx.New()
// _, err := httpx.Head[string](c, "https://httpbin.org/get")
// if err != nil {
// return
// }
func Head[T any](client *Client, url string, opts ...Option) (T, error) {
body, _, err := do[T](client, nil, methodHead, url, nil, opts)
return body, err
}
// Options issues an OPTIONS request using the provided client.
// It remains available for compatibility; new code can use Client.Options.
// @group Requests
//
// Example: OPTIONS request
//
// c := httpx.New()
// _, err := httpx.Options[string](c, "https://httpbin.org/get")
// if err != nil {
// return
// }
func Options[T any](client *Client, url string, opts ...Option) (T, error) {
body, _, err := do[T](client, nil, methodOptions, url, nil, opts)
return body, err
}
// GetCtx issues a GET request using the provided client and context.
// It remains available for compatibility; new code can use Client.GetCtx.
// @group Requests (Context)
//
// Example: context-aware GET
//
// type GetResponse struct {
// URL string `json:"url"`
// }
//
// ctx := context.Background()
// c := httpx.New()
// res, err := httpx.GetCtx[GetResponse](c, ctx, "https://httpbin.org/get")
// if err != nil {
// return
// }
// httpx.Dump(res) // dumps GetResponse
// // #GetResponse {
// // URL => "https://httpbin.org/get" #string
// // }
func GetCtx[T any](client *Client, ctx context.Context, url string, opts ...Option) (T, error) {
body, _, err := do[T](client, ctx, methodGet, url, nil, opts)
return body, err
}
// PostCtx issues a POST request using the provided client and context.
// It remains available for compatibility; new code can use Client.PostCtx.
// @group Requests (Context)
//
// Example: context-aware POST
//
// type CreateUser struct {
// Name string `json:"name"`
// }
// type CreateUserResponse struct {
// JSON CreateUser `json:"json"`
// }
//
// ctx := context.Background()
// c := httpx.New()
// res, err := httpx.PostCtx[CreateUser, CreateUserResponse](c, ctx, "https://httpbin.org/post", CreateUser{Name: "Ana"})
// if err != nil {
// return
// }
// httpx.Dump(res) // dumps CreateUserResponse
// // #CreateUserResponse {
// // JSON => #CreateUser {
// // Name => "Ana" #string
// // }
// // }
func PostCtx[In any, Out any](client *Client, ctx context.Context, url string, body In, opts ...Option) (Out, error) {
out, _, err := do[Out](client, ctx, methodPost, url, body, opts)
return out, err
}
// PutCtx issues a PUT request using the provided client and context.
// It remains available for compatibility; new code can use Client.PutCtx.
// @group Requests (Context)
//
// Example: context-aware PUT
//
// type UpdateUser struct {
// Name string `json:"name"`
// }
// type UpdateUserResponse struct {
// JSON UpdateUser `json:"json"`
// }
//
// ctx := context.Background()
// c := httpx.New()
// res, err := httpx.PutCtx[UpdateUser, UpdateUserResponse](c, ctx, "https://httpbin.org/put", UpdateUser{Name: "Ana"})
// if err != nil {
// return
// }
// httpx.Dump(res) // dumps UpdateUserResponse
// // #UpdateUserResponse {
// // JSON => #UpdateUser {
// // Name => "Ana" #string
// // }
// // }
func PutCtx[In any, Out any](client *Client, ctx context.Context, url string, body In, opts ...Option) (Out, error) {
out, _, err := do[Out](client, ctx, methodPut, url, body, opts)
return out, err
}
// PatchCtx issues a PATCH request using the provided client and context.
// It remains available for compatibility; new code can use Client.PatchCtx.
// @group Requests (Context)
//
// Example: context-aware PATCH
//
// type UpdateUser struct {
// Name string `json:"name"`
// }
// type UpdateUserResponse struct {
// JSON UpdateUser `json:"json"`
// }
//
// ctx := context.Background()
// c := httpx.New()
// res, err := httpx.PatchCtx[UpdateUser, UpdateUserResponse](c, ctx, "https://httpbin.org/patch", UpdateUser{Name: "Ana"})
// if err != nil {
// return
// }
// httpx.Dump(res) // dumps UpdateUserResponse
// // #UpdateUserResponse {
// // JSON => #UpdateUser {
// // Name => "Ana" #string
// // }
// // }
func PatchCtx[In any, Out any](client *Client, ctx context.Context, url string, body In, opts ...Option) (Out, error) {
out, _, err := do[Out](client, ctx, methodPatch, url, body, opts)
return out, err
}
// DeleteCtx issues a DELETE request using the provided client and context.
// It remains available for compatibility; new code can use Client.DeleteCtx.
// @group Requests (Context)
//
// Example: context-aware DELETE
//
// type DeleteResponse struct {
// URL string `json:"url"`
// }
//
// ctx := context.Background()
// c := httpx.New()
// res, err := httpx.DeleteCtx[DeleteResponse](c, ctx, "https://httpbin.org/delete")
// if err != nil {
// return
// }
// httpx.Dump(res) // dumps DeleteResponse
// // #DeleteResponse {
// // URL => "https://httpbin.org/delete" #string
// // }
func DeleteCtx[T any](client *Client, ctx context.Context, url string, opts ...Option) (T, error) {
body, _, err := do[T](client, ctx, methodDelete, url, nil, opts)
return body, err
}
// HeadCtx issues a HEAD request using the provided client and context.
// It remains available for compatibility; new code can use Client.HeadCtx.
// @group Requests (Context)
//
// Example: context-aware HEAD
//
// ctx := context.Background()
// c := httpx.New()
// _, err := httpx.HeadCtx[string](c, ctx, "https://httpbin.org/get")
// if err != nil {
// return
// }
func HeadCtx[T any](client *Client, ctx context.Context, url string, opts ...Option) (T, error) {
body, _, err := do[T](client, ctx, methodHead, url, nil, opts)
return body, err
}
// OptionsCtx issues an OPTIONS request using the provided client and context.
// It remains available for compatibility; new code can use Client.OptionsCtx.
// @group Requests (Context)
//
// Example: context-aware OPTIONS
//
// ctx := context.Background()
// c := httpx.New()
// _, err := httpx.OptionsCtx[string](c, ctx, "https://httpbin.org/get")
// if err != nil {
// return
// }
func OptionsCtx[T any](client *Client, ctx context.Context, url string, opts ...Option) (T, error) {
body, _, err := do[T](client, ctx, methodOptions, url, nil, opts)
return body, err
}
// Do executes a pre-configured req request and returns the decoded body and response.
// This is the low-level escape hatch when you need full req control.
// @group Requests
//
// Example: advanced request with response access
//
// r := req.C().R().SetHeader("X-Trace", "1")
// r.SetURL("https://httpbin.org/headers")
// r.Method = http.MethodGet
//
// res, rawResp, err := httpx.Do[map[string]any](r)
// if err != nil {
// return
// }
// httpx.Dump(res) // dumps map[string]any
// // #map[string]interface {} {
// // headers => #map[string]interface {} {
// // X-Trace => "1" #string
// // }
// // }
// println(rawResp.StatusCode)
func Do[T any](r *req.Request) (T, *req.Response, error) {
var out T
if r == nil {
return out, nil, fmt.Errorf("httpx: nil request")
}
rawKind := rawKindOf[T]()
if rawKind == rawNone {
r.SetSuccessResult(&out)
}
resp := r.Do()
if resp.Err != nil {
return out, resp, resp.Err
}
if resp.IsSuccessState() {
if rawKind != rawNone {
out = decodeRaw[T](resp)
}
if rawKind == rawNone && isEmptyBody(resp) {
ensureNonNil(&out)
}
return out, resp, nil
}
return out, resp, newHTTPError(resp)
}
func do[T any](client *Client, ctx context.Context, method, url string, body any, opts []Option) (T, *req.Response, error) {
var out T
if client == nil {
client = Default()
}
if len(opts) != 0 {
client = client.clone()
for _, opt := range opts {
if opt == nil {
continue
}
opt.applyClient(client)
}
}
req := client.req.R()
if ctx != nil {
req.SetContext(ctx)
}
if body != nil {
setBody(req, body)
}
for _, opt := range opts {
if opt == nil {
continue
}
opt.applyRequest(req)
}
rawKind := rawKindOf[T]()
if rawKind == rawNone {
req.SetSuccessResult(&out)
}
resp, err := send(req, method, url)
if err != nil {
if resp != nil && resp.IsSuccessState() && rawKind == rawNone && isEmptyBody(resp) {
ensureNonNil(&out)
return out, resp, nil
}
return out, resp, err
}
if resp.IsSuccessState() {
if rawKind != rawNone {
out = decodeRaw[T](resp)
}
if rawKind == rawNone {
ensureNonNil(&out)
}
return out, resp, nil
}
return out, resp, client.mapError(resp)
}
func (c *Client) mapError(resp *req.Response) error {
if c.errorMapper != nil {
return c.errorMapper(resp)
}
return newHTTPError(resp)
}
const (
methodGet = "GET"
methodPost = "POST"
methodPut = "PUT"
methodPatch = "PATCH"
methodDelete = "DELETE"
methodHead = "HEAD"
methodOptions = "OPTIONS"
)
func send(r *req.Request, method, url string) (*req.Response, error) {
switch method {
case methodGet:
return r.Get(url)
case methodPost:
return r.Post(url)
case methodPut:
return r.Put(url)
case methodPatch:
return r.Patch(url)
case methodDelete:
return r.Delete(url)
case methodHead:
return r.Head(url)
case methodOptions:
return r.Options(url)
default:
return nil, fmt.Errorf("httpx: unsupported method %s", method)
}
}