-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.go
More file actions
92 lines (76 loc) · 2.18 KB
/
Copy pathclient.go
File metadata and controls
92 lines (76 loc) · 2.18 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
package httpclient
import (
"crypto/tls"
"fmt"
"net"
"net/http"
"time"
)
// New builds a new *http.Client
func New(opts ...Option) (*http.Client, error) {
c := &http.Client{}
return c, Apply(c, opts...)
}
// Apply applies options to an existing client
func Apply(c *http.Client, opts ...Option) error {
for _, opt := range opts {
err := opt.Apply(c)
if err != nil {
return err
}
}
return nil
}
func newDefaultTransport() *http.Transport {
return &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second, // nolint: mnd
KeepAlive: 30 * time.Second, // nolint: mnd
}).DialContext,
MaxIdleConns: 100, // nolint: mnd
IdleConnTimeout: 90 * time.Second, // nolint: mnd
TLSHandshakeTimeout: 10 * time.Second, // nolint: mnd
ExpectContinueTimeout: 1 * time.Second, // nolint: mnd
}
}
// Option is a configuration option for building an http.Client
type Option interface {
Apply(*http.Client) error
}
// OptionFunc adapts a function to the Option interface
type OptionFunc func(*http.Client) error
// Apply implements Option
func (f OptionFunc) Apply(c *http.Client) error {
return f(c)
}
// TransportOption configures the client's transport
type TransportOption func(transport *http.Transport) error
// Apply implements Option
func (f TransportOption) Apply(c *http.Client) error {
var transport *http.Transport
rt := c.Transport
switch t := rt.(type) {
case nil:
transport = newDefaultTransport()
c.Transport = transport
case *http.Transport:
transport = t
default:
return fmt.Errorf("%w: transport is of type %T not *http.Transport", ErrInvalidTransportType, c.Transport)
}
return f(transport)
}
// A TLSOption is a type of Option which configures the TLS configuration of the client
type TLSOption func(c *tls.Config) error
// Apply implements Option
func (f TLSOption) Apply(c *http.Client) error {
return TransportOption(func(t *http.Transport) error {
if t.TLSClientConfig == nil {
t.TLSClientConfig = &tls.Config{
MinVersion: tls.VersionTLS12,
}
}
return f(t.TLSClientConfig)
}).Apply(c)
}