-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient.go
More file actions
856 lines (727 loc) · 24.4 KB
/
client.go
File metadata and controls
856 lines (727 loc) · 24.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
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
package requests
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"net"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"path/filepath"
"slices"
"sync"
"time"
"golang.org/x/net/http2"
)
// Client represents an HTTP client.
type Client struct {
mu sync.RWMutex
BaseURL string // BaseURL is prepended to relative request paths.
Headers *http.Header // Headers contains the default headers sent with each request.
Cookies []*http.Cookie // Cookies contains the default cookies sent with each request.
Middlewares []Middleware // Middlewares contains the client-level middleware chain.
TLSConfig *tls.Config // TLSConfig configures TLS settings for the underlying transport.
MaxRetries int // MaxRetries is the maximum number of retry attempts.
RetryStrategy BackoffStrategy // RetryStrategy computes the delay before the next retry.
RetryIf RetryIfFunc // RetryIf decides whether a request should be retried.
HTTPClient *http.Client // HTTPClient is the underlying HTTP client used to send requests.
JSONEncoder Encoder // JSONEncoder encodes JSON request bodies.
JSONDecoder Decoder // JSONDecoder decodes JSON response bodies.
XMLEncoder Encoder // XMLEncoder encodes XML request bodies.
XMLDecoder Decoder // XMLDecoder decodes XML response bodies.
YAMLEncoder Encoder // YAMLEncoder encodes YAML request bodies.
YAMLDecoder Decoder // YAMLDecoder decodes YAML response bodies.
Logger Logger // Logger receives client log output when configured.
auth AuthMethod
}
// Config sets up the initial configuration for the HTTP client.
type Config struct {
BaseURL string // BaseURL is the base URL for requests made by this client.
Headers *http.Header // Headers contains the default headers sent with each request.
Cookies map[string]string // Cookies contains the default cookies sent with each request.
Timeout time.Duration // Timeout is the default request timeout.
CookieJar *cookiejar.Jar // CookieJar stores and sends cookies for the client.
Middlewares []Middleware // Middlewares contains the middleware stack for request and response handling.
TLSConfig *tls.Config // TLSConfig configures TLS settings for the client.
TLSClientCertFile string // TLSClientCertFile is the path to the client certificate file.
TLSClientKeyFile string // TLSClientKeyFile is the path to the client private key file.
TLSServerName string // TLSServerName is the TLS server name used for SNI.
Transport http.RoundTripper // Transport is the custom transport used by the client.
MaxRetries int // MaxRetries is the maximum number of retry attempts.
RetryStrategy BackoffStrategy // RetryStrategy computes the delay before the next retry.
RetryIf RetryIfFunc // RetryIf decides whether a request should be retried.
Logger Logger // Logger receives client log output when configured.
HTTP2 bool // HTTP2 enables HTTP/2 when Transport is not provided.
// Transport-level timeouts.
DialTimeout time.Duration // DialTimeout is the TCP connection timeout.
TLSHandshakeTimeout time.Duration // TLSHandshakeTimeout is the TLS handshake timeout.
ResponseHeaderTimeout time.Duration // ResponseHeaderTimeout is the time to the first response byte.
// Connection pool settings.
MaxIdleConns int // MaxIdleConns is the maximum number of idle connections across all hosts.
MaxIdleConnsPerHost int // MaxIdleConnsPerHost is the maximum number of idle connections per host.
MaxConnsPerHost int // MaxConnsPerHost is the maximum number of connections per host.
IdleConnTimeout time.Duration // IdleConnTimeout is how long idle connections remain open.
}
type clientSnapshot struct {
BaseURL string
Headers http.Header
Cookies []*http.Cookie
Middlewares []Middleware
MaxRetries int
RetryStrategy BackoffStrategy
RetryIf RetryIfFunc
HTTPClient *http.Client
JSONEncoder Encoder
XMLEncoder Encoder
YAMLEncoder Encoder
Logger Logger
auth AuthMethod
}
// Validate checks whether the config contains deterministic invalid values.
func (cfg *Config) Validate() error {
var errs []error
if _, err := url.Parse(cfg.BaseURL); cfg.BaseURL != "" && err != nil {
errs = append(errs, fmt.Errorf("invalid BaseURL: %w", err))
}
if cfg.Timeout < 0 {
errs = append(errs, fmt.Errorf("%w: Timeout", ErrInvalidConfigValue))
}
if cfg.DialTimeout < 0 {
errs = append(errs, fmt.Errorf("%w: DialTimeout", ErrInvalidConfigValue))
}
if cfg.TLSHandshakeTimeout < 0 {
errs = append(errs, fmt.Errorf("%w: TLSHandshakeTimeout", ErrInvalidConfigValue))
}
if cfg.ResponseHeaderTimeout < 0 {
errs = append(errs, fmt.Errorf("%w: ResponseHeaderTimeout", ErrInvalidConfigValue))
}
if cfg.IdleConnTimeout < 0 {
errs = append(errs, fmt.Errorf("%w: IdleConnTimeout", ErrInvalidConfigValue))
}
if cfg.MaxRetries < 0 {
errs = append(errs, fmt.Errorf("%w: MaxRetries", ErrInvalidConfigValue))
}
if cfg.MaxIdleConns < 0 {
errs = append(errs, fmt.Errorf("%w: MaxIdleConns", ErrInvalidConfigValue))
}
if cfg.MaxIdleConnsPerHost < 0 {
errs = append(errs, fmt.Errorf("%w: MaxIdleConnsPerHost", ErrInvalidConfigValue))
}
if cfg.MaxConnsPerHost < 0 {
errs = append(errs, fmt.Errorf("%w: MaxConnsPerHost", ErrInvalidConfigValue))
}
if (cfg.TLSClientCertFile == "") != (cfg.TLSClientKeyFile == "") {
errs = append(errs, ErrInvalidTLSClientCertificateConfig)
}
return errors.Join(errs...)
}
// hasTransportConfig checks if any transport-level configuration is set.
func (cfg *Config) hasTransportConfig() bool {
return cfg.DialTimeout > 0 || cfg.TLSHandshakeTimeout > 0 ||
cfg.ResponseHeaderTimeout > 0 || cfg.MaxIdleConns > 0 ||
cfg.MaxIdleConnsPerHost > 0 || cfg.MaxConnsPerHost > 0 ||
cfg.IdleConnTimeout > 0
}
// New creates a Client with functional options applied.
// It calls Create(nil) to initialize a client with default settings,
// then applies each option in order.
func New(opts ...ClientOption) *Client {
c := Create(nil)
for _, opt := range opts {
opt(c)
}
return c
}
// URL creates a new HTTP client with the given base URL.
func URL(baseURL string) *Client {
return Create(&Config{BaseURL: baseURL})
}
// Create initializes a new HTTP client with the given configuration.
func Create(config *Config) *Client {
if config == nil {
config = &Config{}
}
httpClient := &http.Client{}
if config.Transport != nil {
httpClient.Transport = config.Transport
}
if config.Timeout != 0 {
httpClient.Timeout = config.Timeout
}
if config.CookieJar != nil {
httpClient.Jar = config.CookieJar
}
client := &Client{
BaseURL: config.BaseURL,
Headers: config.Headers,
HTTPClient: httpClient,
JSONEncoder: DefaultJSONEncoder,
JSONDecoder: DefaultJSONDecoder,
XMLEncoder: DefaultXMLEncoder,
XMLDecoder: DefaultXMLDecoder,
YAMLEncoder: DefaultYAMLEncoder,
YAMLDecoder: DefaultYAMLDecoder,
TLSConfig: config.TLSConfig,
}
if config.TLSServerName != "" {
if client.TLSConfig == nil {
client.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
}
client.TLSConfig.ServerName = config.TLSServerName
}
if config.TLSClientCertFile != "" && config.TLSClientKeyFile != "" {
cert, err := tls.LoadX509KeyPair(filepath.Clean(config.TLSClientCertFile), filepath.Clean(config.TLSClientKeyFile))
if err == nil {
if client.TLSConfig == nil {
client.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
}
client.TLSConfig.Certificates = []tls.Certificate{cert}
}
}
switch {
case client.TLSConfig != nil && config.HTTP2:
client.HTTPClient.Transport = &http2.Transport{
TLSClientConfig: client.TLSConfig,
}
case client.TLSConfig != nil:
if httpClient.Transport != nil {
if transport, ok := httpClient.Transport.(*http.Transport); ok {
transport.TLSClientConfig = client.TLSConfig
}
} else {
client.HTTPClient.Transport = &http.Transport{
TLSClientConfig: client.TLSConfig,
}
}
case config.HTTP2:
client.HTTPClient.Transport = &http2.Transport{}
}
// Apply transport-level timeouts and connection pool settings
applyTransportConfig(client, config)
if config.Middlewares != nil {
client.Middlewares = config.Middlewares
}
if config.Cookies != nil {
client.SetDefaultCookies(config.Cookies)
}
if config.MaxRetries != 0 {
client.MaxRetries = config.MaxRetries
}
if config.RetryStrategy != nil {
client.RetryStrategy = config.RetryStrategy
} else {
client.RetryStrategy = DefaultBackoffStrategy(1 * time.Second)
}
if config.RetryIf != nil {
client.RetryIf = config.RetryIf
} else {
client.RetryIf = DefaultRetryIf
}
if config.Logger != nil {
client.Logger = config.Logger
}
return client
}
// SetBaseURL sets the base URL for the client.
func (c *Client) SetBaseURL(baseURL string) {
c.mu.Lock()
defer c.mu.Unlock()
c.BaseURL = baseURL
}
// AddMiddleware adds a middleware to the client.
func (c *Client) AddMiddleware(middlewares ...Middleware) {
c.mu.Lock()
defer c.mu.Unlock()
c.Middlewares = append(c.Middlewares, middlewares...)
}
func (c *Client) syncTLSConfigLocked() {
if c.HTTPClient == nil {
c.HTTPClient = &http.Client{}
}
if c.TLSConfig == nil {
return
}
if transport, ok := c.HTTPClient.Transport.(*http.Transport); ok {
transport.TLSClientConfig = c.TLSConfig
return
}
c.HTTPClient.Transport = &http.Transport{TLSClientConfig: c.TLSConfig}
}
// SetTLSConfig sets the TLS configuration for the client.
func (c *Client) SetTLSConfig(config *tls.Config) *Client {
c.mu.Lock()
defer c.mu.Unlock()
c.TLSConfig = config
c.syncTLSConfigLocked()
return c
}
// ensureTLSConfig initializes the TLS configuration if nil.
// Must be called with c.mu held.
func (c *Client) ensureTLSConfig() {
if c.TLSConfig == nil {
c.TLSConfig = &tls.Config{
MinVersion: tls.VersionTLS12,
}
}
}
// InsecureSkipVerify sets the TLS configuration to skip certificate verification.
func (c *Client) InsecureSkipVerify() *Client {
c.mu.Lock()
defer c.mu.Unlock()
c.ensureTLSConfig()
c.TLSConfig.InsecureSkipVerify = true
c.syncTLSConfigLocked()
return c
}
// SetCertificates sets the TLS certificates for the client.
func (c *Client) SetCertificates(certs ...tls.Certificate) *Client {
c.mu.Lock()
defer c.mu.Unlock()
c.ensureTLSConfig()
c.TLSConfig.Certificates = certs
c.syncTLSConfigLocked()
return c
}
// SetClientCertificate loads and sets a client certificate and private key from files.
func (c *Client) SetClientCertificate(certFile, keyFile string) *Client {
cert, err := tls.LoadX509KeyPair(filepath.Clean(certFile), filepath.Clean(keyFile))
if err != nil {
if c.Logger != nil {
c.Logger.Errorf("failed to load client certificate: %v", err)
}
return c
}
return c.SetCertificates(cert)
}
// SetTLSServerName sets the TLS server name (SNI) for the client.
func (c *Client) SetTLSServerName(serverName string) *Client {
c.mu.Lock()
defer c.mu.Unlock()
c.ensureTLSConfig()
c.TLSConfig.ServerName = serverName
c.syncTLSConfigLocked()
return c
}
// SetRootCertificate sets the root certificate for the client.
func (c *Client) SetRootCertificate(pemFilePath string) *Client {
cleanPath := filepath.Clean(pemFilePath)
rootPemData, err := os.ReadFile(cleanPath)
if err != nil {
if c.Logger != nil {
c.Logger.Errorf("failed to read root certificate: %v", err)
}
return c
}
return c.handleCAs("root", rootPemData)
}
// SetRootCertificateFromString sets the root certificate for the client from a string.
func (c *Client) SetRootCertificateFromString(pemCerts string) *Client {
return c.handleCAs("root", []byte(pemCerts))
}
// SetClientRootCertificate sets the client root certificate for the client.
func (c *Client) SetClientRootCertificate(pemFilePath string) *Client {
cleanPath := filepath.Clean(pemFilePath)
rootPemData, err := os.ReadFile(cleanPath)
if err != nil {
if c.Logger != nil {
c.Logger.Errorf("failed to read client root certificate: %v", err)
}
return c
}
return c.handleCAs("client", rootPemData)
}
// SetClientRootCertificateFromString sets the client root certificate for the client from a string.
func (c *Client) SetClientRootCertificateFromString(pemCerts string) *Client {
return c.handleCAs("client", []byte(pemCerts))
}
// handleCAs sets the TLS certificates for the client.
func (c *Client) handleCAs(scope string, pemCerts []byte) *Client {
c.mu.Lock()
defer c.mu.Unlock()
c.ensureTLSConfig()
switch scope {
case "root":
if c.TLSConfig.RootCAs == nil {
c.TLSConfig.RootCAs = x509.NewCertPool()
}
c.TLSConfig.RootCAs.AppendCertsFromPEM(pemCerts)
case "client":
if c.TLSConfig.ClientCAs == nil {
c.TLSConfig.ClientCAs = x509.NewCertPool()
}
c.TLSConfig.ClientCAs.AppendCertsFromPEM(pemCerts)
}
c.syncTLSConfigLocked()
return c
}
// SetHTTPClient sets the HTTP client for the client.
func (c *Client) SetHTTPClient(httpClient *http.Client) {
c.mu.Lock()
defer c.mu.Unlock()
c.HTTPClient = httpClient
}
// SetDefaultHeaders sets the default headers for the client.
func (c *Client) SetDefaultHeaders(headers *http.Header) {
c.mu.Lock()
defer c.mu.Unlock()
c.Headers = headers
}
// SetDefaultHeader adds or updates a default header.
func (c *Client) SetDefaultHeader(key, value string) {
c.mu.Lock()
defer c.mu.Unlock()
if c.Headers == nil {
c.Headers = &http.Header{}
}
c.Headers.Set(key, value)
}
// AddDefaultHeader adds a default header.
func (c *Client) AddDefaultHeader(key, value string) {
c.mu.Lock()
defer c.mu.Unlock()
if c.Headers == nil {
c.Headers = &http.Header{}
}
c.Headers.Add(key, value)
}
// DelDefaultHeader removes a default header.
func (c *Client) DelDefaultHeader(key string) {
c.mu.Lock()
defer c.mu.Unlock()
if c.Headers == nil {
return
}
c.Headers.Del(key)
}
// SetDefaultContentType sets the default content type for the client.
func (c *Client) SetDefaultContentType(contentType string) {
c.SetDefaultHeader("Content-Type", contentType)
}
// SetDefaultAccept sets the default accept header for the client.
func (c *Client) SetDefaultAccept(accept string) {
c.SetDefaultHeader("Accept", accept)
}
// SetDefaultUserAgent sets the default user agent for the client.
func (c *Client) SetDefaultUserAgent(userAgent string) {
c.SetDefaultHeader("User-Agent", userAgent)
}
// SetDefaultReferer sets the default referer for the client.
func (c *Client) SetDefaultReferer(referer string) {
c.SetDefaultHeader("Referer", referer)
}
// SetDefaultTimeout sets the default timeout for the client.
func (c *Client) SetDefaultTimeout(timeout time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.HTTPClient.Timeout = timeout
}
// SetDefaultTransport sets the default transport for the client.
func (c *Client) SetDefaultTransport(transport http.RoundTripper) {
c.mu.Lock()
defer c.mu.Unlock()
c.HTTPClient.Transport = transport
}
// SetDefaultCookieJar sets the default cookie jar for the client.
func (c *Client) SetDefaultCookieJar(jar *cookiejar.Jar) {
c.mu.Lock()
defer c.mu.Unlock()
c.HTTPClient.Jar = jar
}
// SetDefaultCookies sets the default cookies for the client.
func (c *Client) SetDefaultCookies(cookies map[string]string) {
for name, value := range cookies {
c.SetDefaultCookie(name, value)
}
}
// SetDefaultCookie sets a default cookie for the client.
func (c *Client) SetDefaultCookie(name, value string) {
c.mu.Lock()
defer c.mu.Unlock()
c.Cookies = append(c.Cookies, &http.Cookie{Name: name, Value: value})
}
// DelDefaultCookie removes a default cookie from the client.
func (c *Client) DelDefaultCookie(name string) {
c.mu.Lock()
defer c.mu.Unlock()
if c.Cookies == nil {
return
}
c.Cookies = slices.DeleteFunc(c.Cookies, func(cookie *http.Cookie) bool {
return cookie.Name == name
})
}
// SetJSONMarshal sets the JSON marshal function for the client's JSONEncoder.
func (c *Client) SetJSONMarshal(marshalFunc func(v any) ([]byte, error)) {
c.mu.Lock()
defer c.mu.Unlock()
c.JSONEncoder = &JSONEncoder{
MarshalFunc: marshalFunc,
}
}
// SetJSONUnmarshal sets the JSON unmarshal function for the client's JSONDecoder.
func (c *Client) SetJSONUnmarshal(unmarshalFunc func(data []byte, v any) error) {
c.mu.Lock()
defer c.mu.Unlock()
c.JSONDecoder = &JSONDecoder{
UnmarshalFunc: unmarshalFunc,
}
}
// SetXMLMarshal sets the XML marshal function for the client's XMLEncoder.
func (c *Client) SetXMLMarshal(marshalFunc func(v any) ([]byte, error)) {
c.mu.Lock()
defer c.mu.Unlock()
c.XMLEncoder = &XMLEncoder{
MarshalFunc: marshalFunc,
}
}
// SetXMLUnmarshal sets the XML unmarshal function for the client's XMLDecoder.
func (c *Client) SetXMLUnmarshal(unmarshalFunc func(data []byte, v any) error) {
c.mu.Lock()
defer c.mu.Unlock()
c.XMLDecoder = &XMLDecoder{
UnmarshalFunc: unmarshalFunc,
}
}
// SetYAMLMarshal sets the YAML marshal function for the client's YAMLEncoder.
func (c *Client) SetYAMLMarshal(marshalFunc func(v any) ([]byte, error)) {
c.mu.Lock()
defer c.mu.Unlock()
c.YAMLEncoder = &YAMLEncoder{
MarshalFunc: marshalFunc,
}
}
// SetYAMLUnmarshal sets the YAML unmarshal function for the client's YAMLDecoder.
func (c *Client) SetYAMLUnmarshal(unmarshalFunc func(data []byte, v any) error) {
c.mu.Lock()
defer c.mu.Unlock()
c.YAMLDecoder = &YAMLDecoder{
UnmarshalFunc: unmarshalFunc,
}
}
func (c *Client) snapshot() clientSnapshot {
c.mu.RLock()
defer c.mu.RUnlock()
headers := http.Header{}
if c.Headers != nil {
headers = c.Headers.Clone()
}
cookies := make([]*http.Cookie, len(c.Cookies))
for i, cookie := range c.Cookies {
if cookie == nil {
continue
}
clone := *cookie
clone.Unparsed = slices.Clone(cookie.Unparsed)
cookies[i] = &clone
}
middlewares := slices.Clone(c.Middlewares)
return clientSnapshot{
BaseURL: c.BaseURL,
Headers: headers,
Cookies: cookies,
Middlewares: middlewares,
MaxRetries: c.MaxRetries,
RetryStrategy: c.RetryStrategy,
RetryIf: c.RetryIf,
HTTPClient: c.HTTPClient,
JSONEncoder: c.JSONEncoder,
XMLEncoder: c.XMLEncoder,
YAMLEncoder: c.YAMLEncoder,
Logger: c.Logger,
auth: c.auth,
}
}
// GetHTTPClient returns the underlying HTTP client in a thread-safe way.
func (c *Client) GetHTTPClient() *http.Client {
c.mu.RLock()
defer c.mu.RUnlock()
return c.HTTPClient
}
// GetBaseURL returns the configured base URL in a thread-safe way.
func (c *Client) GetBaseURL() string {
c.mu.RLock()
defer c.mu.RUnlock()
return c.BaseURL
}
// SetMaxRetries sets the maximum number of retry attempts.
func (c *Client) SetMaxRetries(maxRetries int) *Client {
c.mu.Lock()
defer c.mu.Unlock()
c.MaxRetries = maxRetries
return c
}
// SetRetryStrategy sets the backoff strategy for retries.
func (c *Client) SetRetryStrategy(strategy BackoffStrategy) *Client {
c.mu.Lock()
defer c.mu.Unlock()
c.RetryStrategy = strategy
return c
}
// SetRetryIf sets the custom retry condition function.
func (c *Client) SetRetryIf(retryIf RetryIfFunc) *Client {
c.mu.Lock()
defer c.mu.Unlock()
c.RetryIf = retryIf
return c
}
// SetAuth configures an authentication method for the client.
func (c *Client) SetAuth(auth AuthMethod) {
c.mu.Lock()
defer c.mu.Unlock()
if auth.Valid() {
c.auth = auth
}
}
// SetRedirectPolicy sets the redirect policy for the client.
func (c *Client) SetRedirectPolicy(policies ...RedirectPolicy) *Client {
c.mu.Lock()
defer c.mu.Unlock()
c.HTTPClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
for _, p := range policies {
if err := p.Apply(req, via); err != nil {
return err
}
}
return nil
}
return c
}
// SetLogger sets logger instance in client.
func (c *Client) SetLogger(logger Logger) *Client {
c.mu.Lock()
defer c.mu.Unlock()
c.Logger = logger
return c
}
// withTransport executes a function on the client's transport, handling locking and error checking.
// Returns the client for method chaining. Errors from ensureTransport are silently ignored to
// maintain the fluent API pattern.
func (c *Client) withTransport(fn func(*http.Transport)) *Client {
c.mu.Lock()
defer c.mu.Unlock()
transport, err := c.ensureTransport()
if err != nil {
return c
}
fn(transport)
return c
}
// SetDialTimeout sets the TCP connection timeout on the underlying transport.
func (c *Client) SetDialTimeout(d time.Duration) *Client {
return c.withTransport(func(t *http.Transport) {
t.DialContext = (&net.Dialer{Timeout: d}).DialContext
})
}
// SetTLSHandshakeTimeout sets the TLS handshake timeout on the underlying transport.
func (c *Client) SetTLSHandshakeTimeout(d time.Duration) *Client {
return c.withTransport(func(t *http.Transport) {
t.TLSHandshakeTimeout = d
})
}
// SetResponseHeaderTimeout sets the time to wait for response headers after the request
// is sent. This does not include the time to read the response body.
func (c *Client) SetResponseHeaderTimeout(d time.Duration) *Client {
return c.withTransport(func(t *http.Transport) {
t.ResponseHeaderTimeout = d
})
}
// SetMaxIdleConns sets the maximum number of idle connections across all hosts.
func (c *Client) SetMaxIdleConns(n int) *Client {
return c.withTransport(func(t *http.Transport) {
t.MaxIdleConns = n
})
}
// SetMaxIdleConnsPerHost sets the maximum number of idle connections per host.
func (c *Client) SetMaxIdleConnsPerHost(n int) *Client {
return c.withTransport(func(t *http.Transport) {
t.MaxIdleConnsPerHost = n
})
}
// SetMaxConnsPerHost sets the maximum total number of connections per host.
func (c *Client) SetMaxConnsPerHost(n int) *Client {
return c.withTransport(func(t *http.Transport) {
t.MaxConnsPerHost = n
})
}
// SetIdleConnTimeout sets how long idle connections remain in the pool before being closed.
func (c *Client) SetIdleConnTimeout(d time.Duration) *Client {
return c.withTransport(func(t *http.Transport) {
t.IdleConnTimeout = d
})
}
// applyTransportConfig applies transport-level timeouts and connection pool settings
// from Config to the client's transport. Only modifies settings that are explicitly set
// (non-zero). Skips if the transport is not *http.Transport (e.g., HTTP/2 transport).
func applyTransportConfig(c *Client, config *Config) {
transport, ok := c.HTTPClient.Transport.(*http.Transport)
if !ok && (c.HTTPClient.Transport != nil || !config.hasTransportConfig()) {
return
}
if !ok {
transport = &http.Transport{}
c.HTTPClient.Transport = transport
}
if config.DialTimeout > 0 {
transport.DialContext = (&net.Dialer{Timeout: config.DialTimeout}).DialContext
}
if config.TLSHandshakeTimeout > 0 {
transport.TLSHandshakeTimeout = config.TLSHandshakeTimeout
}
if config.ResponseHeaderTimeout > 0 {
transport.ResponseHeaderTimeout = config.ResponseHeaderTimeout
}
if config.MaxIdleConns > 0 {
transport.MaxIdleConns = config.MaxIdleConns
}
if config.MaxIdleConnsPerHost > 0 {
transport.MaxIdleConnsPerHost = config.MaxIdleConnsPerHost
}
if config.MaxConnsPerHost > 0 {
transport.MaxConnsPerHost = config.MaxConnsPerHost
}
if config.IdleConnTimeout > 0 {
transport.IdleConnTimeout = config.IdleConnTimeout
}
}
// Get initiates a GET request.
func (c *Client) Get(path string) *RequestBuilder {
return c.NewRequestBuilder(http.MethodGet, path)
}
// Post initiates a POST request.
func (c *Client) Post(path string) *RequestBuilder {
return c.NewRequestBuilder(http.MethodPost, path)
}
// Delete initiates a DELETE request.
func (c *Client) Delete(path string) *RequestBuilder {
return c.NewRequestBuilder(http.MethodDelete, path)
}
// Put initiates a PUT request.
func (c *Client) Put(path string) *RequestBuilder {
return c.NewRequestBuilder(http.MethodPut, path)
}
// Patch initiates a PATCH request.
func (c *Client) Patch(path string) *RequestBuilder {
return c.NewRequestBuilder(http.MethodPatch, path)
}
// Options initiates an OPTIONS request.
func (c *Client) Options(path string) *RequestBuilder {
return c.NewRequestBuilder(http.MethodOptions, path)
}
// Head initiates a HEAD request.
func (c *Client) Head(path string) *RequestBuilder {
return c.NewRequestBuilder(http.MethodHead, path)
}
// Connect initiates a CONNECT request.
func (c *Client) Connect(path string) *RequestBuilder {
return c.NewRequestBuilder(http.MethodConnect, path)
}
// Trace initiates a TRACE request.
func (c *Client) Trace(path string) *RequestBuilder {
return c.NewRequestBuilder(http.MethodTrace, path)
}
// Custom initiates a custom request.
func (c *Client) Custom(path, method string) *RequestBuilder {
return c.NewRequestBuilder(method, path)
}