Repository navigation
Expand file tree
/
Copy pathclient.go
More file actions
748 lines (634 loc) · 21.3 KB
/
Copy pathclient.go
File metadata and controls
748 lines (634 loc) · 21.3 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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
package greq
import (
"context"
"fmt"
"io"
"net"
"net/http"
"strings"
"time"
"github.com/gookit/goutil/netutil/httpctype"
"github.com/gookit/goutil/netutil/httpheader"
"github.com/gookit/goutil/netutil/httpreq"
"github.com/gookit/goutil/strutil"
"github.com/gookit/greq/ext/httpfile"
"github.com/gookit/greq/internal/bodyprovider"
)
// Client is an HTTP Request builder and sender.
type Client struct {
doer httpreq.Doer
// core handler.
handler HandleFunc
middles []Middleware
//
// default options for all requests
//
// Method default http method. default is GET
Method string
// Header default http header. default is nil
Header http.Header
// defalut content type
ContentType string
// BaseURL default base URL. default is ""
BaseURL string
// Timeout default timeout(ms) for each request. default 10s
//
// - 0: not limit
Timeout int
// RespDecoder response data decoder.
// - use for create Response instance. default is JSON decoder
RespDecoder RespDecoder
// ReqVars template vars for request: URL, Header, Query, Body
//
// eg: http://example.com/${name}
ReqVars map[string]string
// BeforeSend callback on each request, can return error to deny request.
BeforeSend func(r *http.Request) error
// AfterSend callback on each request, can use for record request and response
AfterSend AfterSendFn
//
// default retry config
//
// MaxRetries max retry times. default is 0 (not retry)
MaxRetries int
// RetryDelay retry delay time (ms). default is 0 (no delay)
RetryDelay int
// RetryChecker retry condition checker. default is nil (not retry)
RetryChecker RetryChecker
}
// NewClient create a new http request client. alias of New()
func NewClient(baseURL ...string) *Client { return New(baseURL...) }
// New create a new http request client.
func New(baseURL ...string) *Client {
h := &Client{
doer: &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 200,
MaxIdleConnsPerHost: 50,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
},
Timeout: 10000,
Method: http.MethodGet,
Header: make(http.Header),
RespDecoder: jsonDecoder{},
}
if len(baseURL) > 0 {
h.BaseURL = baseURL[0]
}
// Build the handler chain once at construction time. Concurrent requests
// only READ h.handler; rebuilding happens only when Middlewares() is called.
h.wrapMiddlewares()
return h
}
// Sub create an instance from current. will inherit all options
func (h *Client) Sub() *Client {
// copy Header pairs into new Header map
headerCopy := make(http.Header)
for k, v := range h.Header {
headerCopy[k] = v
}
sub := &Client{
doer: h.doer,
Method: h.Method,
BaseURL: h.BaseURL,
Header: headerCopy,
ContentType: h.ContentType,
Timeout: h.Timeout,
RespDecoder: h.RespDecoder,
MaxRetries: h.MaxRetries,
RetryDelay: h.RetryDelay,
RetryChecker: h.RetryChecker,
BeforeSend: h.BeforeSend,
AfterSend: h.AfterSend,
}
sub.wrapMiddlewares() // build the sub-client's own handler chain
return sub
}
//
// region Config
// ----------------------------
// WithRetryConfig set retry configuration
func (h *Client) WithRetryConfig(maxRetries, retryDelay int, checker RetryChecker) *Client {
h.MaxRetries = maxRetries
h.RetryDelay = retryDelay
h.RetryChecker = checker
return h
}
// WithMaxRetries set max retry times
func (h *Client) WithMaxRetries(maxRetries int) *Client {
h.MaxRetries = maxRetries
return h
}
// WithRetryDelay set retry delay time in milliseconds
func (h *Client) WithRetryDelay(retryDelay int) *Client {
h.RetryDelay = retryDelay
return h
}
// WithRetryChecker set custom retry checker function
func (h *Client) WithRetryChecker(checker RetryChecker) *Client {
h.RetryChecker = checker
return h
}
// Doer custom set http request doer.
// If a nil cli is given, the DefaultDoer will be used.
func (h *Client) Doer(doer httpreq.Doer) *Client {
if doer != nil {
h.doer = doer
} else {
h.doer = DefaultDoer
}
return h
}
// Client custom set http request doer
func (h *Client) Client(doer httpreq.Doer) *Client { return h.Doer(doer) }
// HttpClient custom set http cli as request doer
func (h *Client) HttpClient(hClient *http.Client) *Client { return h.Doer(hClient) }
// Config custom config for client.
//
// Usage:
//
// h.Config(func(h *Client) {
// h.Method = http.MethodPost
// })
func (h *Client) Config(fn func(h *Client)) *Client {
fn(h)
return h
}
// ConfigDoer custom config http request doer
func (h *Client) ConfigDoer(fn func(doer httpreq.Doer)) *Client {
fn(h.doer)
return h
}
// ConfigHClient custom config http client.
//
// Usage:
//
// h.ConfigHClient(func(hClient *http.Client) {
// hClient.Timeout = 30 * time.Second
// })
func (h *Client) ConfigHClient(fn func(hClient *http.Client)) *Client {
if hc, ok := h.doer.(*http.Client); ok {
fn(hc)
} else {
panic("the doer is not an *http.Client")
}
return h
}
// SetMaxIdleConns Set the maximum number of idle connections.
func (h *Client) SetMaxIdleConns(maxIdleConns, maxIdleConnsPerHost int) *Client {
if hc, ok := h.doer.(*http.Client); ok {
if transport, ok := hc.Transport.(*http.Transport); ok && transport != nil {
transport.MaxIdleConns = maxIdleConns
transport.MaxIdleConnsPerHost = maxIdleConnsPerHost
}
}
return h
}
// DefaultTimeout set default timeout in milliseconds for requests. default is 0 (infinite)
func (h *Client) DefaultTimeout(timeoutMs int) *Client {
h.Timeout = timeoutMs
return h
}
// Use one or multi middlewares
func (h *Client) Use(middles ...Middleware) *Client { return h.Middlewares(middles...) }
// Uses one or multi middlewares
func (h *Client) Uses(middles ...Middleware) *Client { return h.Middlewares(middles...) }
// Middleware add one or multi middlewares
func (h *Client) Middleware(middles ...Middleware) *Client { return h.Middlewares(middles...) }
// Middlewares add one or multi middlewares.
//
// Not safe to call concurrently with in-flight requests — call during setup
// before requests are dispatched.
func (h *Client) Middlewares(middles ...Middleware) *Client {
h.middles = append(h.middles, middles...)
h.wrapMiddlewares() // rebuild the chain now so the request hot path stays read-only
return h
}
// WithRespDecoder for cli
func (h *Client) WithRespDecoder(respDecoder RespDecoder) *Client {
h.RespDecoder = respDecoder
return h
}
// OnBeforeSend for cli
func (h *Client) OnBeforeSend(fn func(r *http.Request) error) *Client {
h.BeforeSend = fn
return h
}
// ----------- Header ------------
// DefaultHeader sets the http.Header value, it will be used for all requests.
func (h *Client) DefaultHeader(key, value string) *Client {
h.Header.Set(key, value)
return h
}
// DefaultHeaders sets all the http.Header values, it will be used for all requests.
func (h *Client) DefaultHeaders(headers http.Header) *Client {
h.Header = headers
return h
}
// DefaultContentType set default ContentType header, it will be used for all requests.
//
// Usage:
//
// // json type
// h.DefaultContentType(httpctype.JSON)
// // form type
// h.DefaultContentType(httpctype.Form)
func (h *Client) DefaultContentType(value string) *Client {
h.ContentType = value
return h
}
// DefaultUserAgent with User-Agent header setting for all requests.
func (h *Client) DefaultUserAgent(value string) *Client {
return h.DefaultHeader(httpheader.UserAgent, value)
}
// DefaultUserAuth with user auth header value for all requests.
func (h *Client) DefaultUserAuth(value string) *Client {
return h.DefaultHeader(httpheader.UserAuth, value)
}
// DefaultBasicAuth 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 (h *Client) DefaultBasicAuth(username, password string) *Client {
return h.DefaultHeader(httpheader.UserAuth, httpreq.BuildBasicAuth(username, password))
}
// ------------ Method ------------
// WithBaseURL set default base URL for all request
func (h *Client) WithBaseURL(baseURL string) *Client {
h.BaseURL = baseURL
return h
}
// DefaultMethod set default method name. it will be used when the Get()/Post() method is empty.
func (h *Client) DefaultMethod(method string) *Client {
h.Method = strings.ToUpper(method)
return h
}
// Builder create a new builder with current client.
func (h *Client) Builder(optFns ...OptionFn) *Builder { return BuilderWithClient(h, optFns...) }
//
// region REST Methods
// ------------------------------
//
// Head sets the method to HEAD and request the pathURL, then send request and return response.
func (h *Client) Head(pathURL string) *Builder { return newBuilder(h, http.MethodHead, pathURL) }
// HeadDo sets the method to HEAD and request the pathURL,
// then send request and return response.
func (h *Client) HeadDo(pathURL string, optFns ...OptionFn) (*Response, error) {
return h.SendWithOpt(pathURL, NewOpt2(optFns, http.MethodHead))
}
// Get sets the method to GET and sets the given pathURL
func (h *Client) Get(pathURL string) *Builder { return newBuilder(h, http.MethodGet, pathURL) }
// GetDo sets the method to GET and sets the given pathURL,
// then send request and return response.
func (h *Client) GetDo(pathURL string, optFns ...OptionFn) (*Response, error) {
return h.SendWithOpt(pathURL, NewOpt2(optFns, http.MethodGet))
}
// Post sets the method to POST and sets the given pathURL
func (h *Client) Post(pathURL string) *Builder {
return newBuilder(h, http.MethodPost, pathURL)
}
// PostDo sets the method to POST and sets the given pathURL,
// then send request and return http response.
func (h *Client) PostDo(pathURL string, optFns ...OptionFn) (*Response, error) {
return h.SendWithOpt(pathURL, NewOpt2(optFns, http.MethodPost))
}
// Put sets the method to PUT and sets the given pathURL
func (h *Client) Put(pathURL string) *Builder {
return newBuilder(h, http.MethodPut, pathURL)
}
// PutDo sets the method to PUT and sets the given pathURL,
// then send request and return http response.
func (h *Client) PutDo(pathURL string, optFns ...OptionFn) (*Response, error) {
return h.SendWithOpt(pathURL, NewOpt2(optFns, http.MethodPut))
}
// Patch sets the method to PATCH and sets the given pathURL
func (h *Client) Patch(pathURL string) *Builder {
return newBuilder(h, http.MethodPatch, pathURL)
}
// PatchDo sets the method to PATCH and sets the given pathURL,
// then send request and return http response.
func (h *Client) PatchDo(pathURL string, optFns ...OptionFn) (*Response, error) {
return h.SendWithOpt(pathURL, NewOpt2(optFns, http.MethodPatch))
}
// Delete sets the method to DELETE and sets the given pathURL
func (h *Client) Delete(pathURL string) *Builder {
return newBuilder(h, http.MethodDelete, pathURL)
}
// DeleteDo sets the method to DELETE and sets the given pathURL,
// then send request and return http response.
func (h *Client) DeleteDo(pathURL string, optFns ...OptionFn) (*Response, error) {
return h.SendWithOpt(pathURL, NewOpt2(optFns, http.MethodDelete))
}
// Download remote file from url and save to savePath.
func (h *Client) Download(url, savePath string, optFns ...OptionFn) (int, error) {
resp, err := h.Send(http.MethodGet, url, optFns...)
if err != nil {
return 0, err
}
if resp.IsFail() {
resp.QuietCloseBody()
return 0, fmt.Errorf("Download failed, status code: %d", resp.StatusCode)
}
return resp.SaveFile(savePath)
}
// UploadFile uploads a single file to the given URL.
func (h *Client) UploadFile(pathURL, fieldName, filePath string, optFns ...OptionFn) (*Response, error) {
opt := NewOpt2(optFns, http.MethodPost)
opt.Provider = bodyprovider.NewMultipart(map[string]string{fieldName: filePath}, nil)
return h.SendWithOpt(pathURL, opt)
}
// UploadFiles uploads multiple files to the given URL.
func (h *Client) UploadFiles(pathURL string, files map[string]string, optFns ...OptionFn) (*Response, error) {
opt := NewOpt2(optFns, http.MethodPost)
opt.Provider = bodyprovider.NewMultipart(files, nil)
return h.SendWithOpt(pathURL, opt)
}
// UploadWithData uploads files with additional form fields.
func (h *Client) UploadWithData(pathURL string, files map[string]string, fields map[string]string, optFns ...OptionFn) (*Response, error) {
opt := NewOpt2(optFns, http.MethodPost)
opt.Provider = bodyprovider.NewMultipart(files, fields)
return h.SendWithOpt(pathURL, opt)
}
//
// region Headers
// ----------------------------
// WithContentType with custom Content-Type header
func (h *Client) WithContentType(value string) *Builder {
return BuilderWithClient(h).WithContentType(value)
}
// JSONType with json Content-Type header
func (h *Client) JSONType() *Builder { return BuilderWithClient(h).JSONType() }
// FormType with from Content-Type header
func (h *Client) FormType() *Builder { return BuilderWithClient(h).FormType() }
// UserAgent with User-Agent header setting for all requests.
func (h *Client) UserAgent(value string) *Builder { return BuilderWithClient(h).UserAgent(value) }
// UserAuth with user auth header value for all requests.
func (h *Client) UserAuth(value string) *Builder { return BuilderWithClient(h).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 (h *Client) BasicAuth(username, password string) *Builder {
return BuilderWithClient(h).BasicAuth(username, password)
}
//
// region URL and Query
// ---------------------------
// 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 (h *Client) QueryParams(ps any) *Builder {
return BuilderWithClient(h).QueryParams(ps)
}
//
// region Set Body
// -----------------------------
// Body with custom any type body
func (h *Client) Body(body any) *Builder { return BuilderWithClient(h).AnyBody(body) }
// AnyBody with custom any type body
func (h *Client) AnyBody(body any) *Builder { return BuilderWithClient(h).AnyBody(body) }
// BodyReader with custom io reader body
func (h *Client) BodyReader(r io.Reader) *Builder { return BuilderWithClient(h).BodyReader(r) }
// BodyProvider with custom body provider
func (h *Client) BodyProvider(bp BodyProvider) *Builder { return BuilderWithClient(h).BodyProvider(bp) }
//
// region Send request
// ------------------------------
// Do send request and return response
func (h *Client) Do(method, url string, optFns ...OptionFn) (*Response, error) {
return h.SendWithOption(method, url, optFns...)
}
// Send request and return response, alias of Do()
func (h *Client) Send(method, url string, optFns ...OptionFn) (*Response, error) {
return h.SendWithOption(method, url, optFns...)
}
// MustSend send request and return response, will panic on error
func (h *Client) MustSend(method, url string, optFns ...OptionFn) *Response {
resp, err := h.SendWithOption(method, url, optFns...)
if err != nil {
panic(err)
}
return resp
}
// SendRaw http request text. like IDE .http file contents
//
// Format:
//
// POST https://example.com/path?name=inhere
// Content-Type: application/json
// Accept: */*
//
// <content>
func (h *Client) SendRaw(raw string, varMp map[string]string) (*Response, error) {
rawReq, err := httpfile.ParseRequest(raw)
if err != nil {
return nil, err
}
rawReq.ApplyVars(varMp)
var body = strings.NewReader(rawReq.Body)
fullURL := h.buildFullURL(rawReq.URL)
req, err := http.NewRequest(rawReq.Method, fullURL, body)
if err != nil {
return nil, err
}
// apply headers
if len(rawReq.Headers) > 0 {
httpreq.SetHeaderMap(req, rawReq.Headers)
}
applySpecialHeaders(req)
// apply default content type
if len(h.ContentType) > 0 && req.Header.Get("Content-Type") == "" {
req.Header.Set("Content-Type", h.ContentType)
}
return h.SendRequest(req)
}
// DoWithOption request with options, then return response
func (h *Client) DoWithOption(method, url string, optFns ...OptionFn) (*Response, error) {
return h.SendWithOption(method, url, optFns...)
}
// SendWithOption request with options, then return response
func (h *Client) SendWithOption(method, url string, optFns ...OptionFn) (*Response, error) {
return h.SendWithOpt(url, NewOpt2(optFns, method))
}
// SendWithOpt send request with option, then return response
func (h *Client) SendWithOpt(pathURL string, opt *Options) (*Response, error) {
req, err := h.NewRequestWithOptions(pathURL, opt)
if err != nil {
return nil, err
}
return h.sendRequestWithRetry(req, 0, h.effectiveRetryCfg(opt))
}
// SendRequest sends a pre-built request using the Client-level retry config.
func (h *Client) SendRequest(req *http.Request) (*Response, error) {
return h.sendRequestWithRetry(req, 0, h.effectiveRetryCfg(nil))
}
// retryCfg is the resolved retry policy for one request lifecycle (initial + retries).
// Threading it through the call chain instead of mutating Client fields makes the
// hot path safe for concurrent SendWithOpt callers.
type retryCfg struct {
maxRetries int
retryDelay int
checker RetryChecker
}
// effectiveRetryCfg resolves the per-request retry config, falling back to Client defaults.
func (h *Client) effectiveRetryCfg(opt *Options) retryCfg {
cfg := retryCfg{
maxRetries: h.MaxRetries,
retryDelay: h.RetryDelay,
checker: h.RetryChecker,
}
if opt != nil {
if opt.MaxRetries > 0 {
cfg.maxRetries = opt.MaxRetries
}
if opt.RetryDelay > 0 {
cfg.retryDelay = opt.RetryDelay
}
if opt.RetryChecker != nil {
cfg.checker = opt.RetryChecker
}
}
return cfg
}
// sendRequestWithRetry send request with retry logic.
// h.handler is built in New/Sub/Middlewares; this hot path only reads it.
func (h *Client) sendRequestWithRetry(req *http.Request, attempt int, cfg retryCfg) (*Response, error) {
start := time.Now()
// call before send.
if h.BeforeSend != nil {
if err := h.BeforeSend(req); err != nil {
return nil, fmt.Errorf("before send check failed: %w", err)
}
}
// do send by core handler
resp, err := h.handler(req)
if resp != nil {
resp.CostTime = time.Since(start).Milliseconds()
}
if h.AfterSend != nil {
h.AfterSend(resp, err)
}
if shouldRetry(resp, err, attempt, cfg) {
if cfg.retryDelay > 0 {
time.Sleep(time.Duration(cfg.retryDelay) * time.Millisecond)
}
return h.sendRequestWithRetry(req, attempt+1, cfg)
}
return resp, err
}
// shouldRetry checks the resolved retry config against the current attempt/result.
func shouldRetry(resp *Response, err error, attempt int, cfg retryCfg) bool {
if cfg.maxRetries <= 0 || attempt >= cfg.maxRetries {
return false
}
checker := cfg.checker
if checker == nil {
checker = DefaultRetryChecker
}
return checker(resp, err, attempt)
}
//
// region Build request
// -----------------------------------
// NewRequest build new request
func (h *Client) NewRequest(method, url string, optFns ...OptionFn) (*http.Request, error) {
return h.NewRequestWithOptions(url, NewOpt2(optFns, method))
}
func (h *Client) buildFullURL(url string) string {
fullURL := url
hasScheme := strings.HasPrefix(url, "http")
if len(h.BaseURL) > 0 {
if !hasScheme {
fullURL = h.BaseURL + url
} else if len(url) == 0 {
fullURL = h.BaseURL
}
} else if !hasScheme {
fullURL = "https://" + url
}
return fullURL
}
// NewRequestWithOptions build new request with Options
func (h *Client) NewRequestWithOptions(url string, opt *Options) (*http.Request, error) {
fullURL := h.buildFullURL(url)
opt = orCreate(opt)
ctx := opt.Context
if ctx == nil {
ctx = context.Background()
}
// set default timeout if not set
if opt.Timeout <= 0 {
opt.Timeout = h.Timeout
}
// convert timeout to duration
if opt.Timeout > 0 {
ctx, opt.TCancelFn = context.WithTimeout(ctx, time.Duration(opt.Timeout)*time.Millisecond)
}
// append Query params
qm := opt.Query
if len(qm) > 0 {
fullURL = httpreq.AppendQueryToURLString(fullURL, qm)
}
// make body
var err error
var body io.Reader
if opt.Provider != nil {
body, err = opt.Provider.Body()
if err != nil {
return nil, err
}
if bpTyp := opt.Provider.ContentType(); bpTyp != "" {
opt.ContentType = bpTyp
}
}
cType := strutil.Valid(opt.ContentType, opt.HeaderM[httpctype.Key], h.ContentType)
method := strings.ToUpper(strutil.OrElse(opt.Method, h.Method))
allowBody := httpreq.IsNoBodyMethod(method) == false
// check opt.Data
if opt.Data != nil {
if !allowBody {
body = nil
fullURL = httpreq.AppendQueryToURLString(fullURL, httpreq.MakeQuery(opt.Data))
} else if body == nil {
body = httpreq.MakeBody(opt.Data, cType)
}
}
// check opt.Body
if allowBody && body == nil && opt.Body != nil {
body = httpreq.MakeBody(opt.Body, cType)
}
// create request
req, err := http.NewRequestWithContext(ctx, method, fullURL, body)
if err != nil {
return nil, err
}
// copy and set headers
httpreq.SetHeaders(req, h.Header, opt.Header)
if len(opt.HeaderM) > 0 {
httpreq.SetHeaderMap(req, opt.HeaderM)
}
if len(cType) > 0 {
req.Header.Set(httpheader.ContentType, cType)
}
applySpecialHeaders(req)
return req, err
}
func applySpecialHeaders(req *http.Request) {
if host := req.Header.Get("Host"); host != "" {
req.Host = host
req.Header.Del("Host")
}
}
// String request to string.
func (h *Client) String() string {
r, err := h.NewRequest("", "")
if err != nil {
return ""
}
return httpreq.RequestToString(r)
}