-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptions.go
More file actions
106 lines (93 loc) · 2.28 KB
/
options.go
File metadata and controls
106 lines (93 loc) · 2.28 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
package fetch
import (
"net"
"net/http"
"time"
)
type Options struct {
// Use library's default retry strategy. Default is true
WithRetry bool
// set headers to be send out with every request, default is none
DefaultHeaders map[string]string
// Provide custom retry strategy
RetryStrategy *[]time.Duration
// Provide a custom retry strategy
HTTPClient *http.Client
}
type FnOpts = func(o *Options) error
// WithOpts - use functional options to provide additional config
func WithOpts(opts ...FnOpts) *Options {
o := Options{}
for _, fn := range opts {
if fn == nil {
continue
}
err := fn(&o)
if err != nil {
panic("Error setting functional option")
}
}
return &o
}
// WithDefaultRetryStrategy - use client default retry strategy
func WithDefaultRetryStrategy() FnOpts {
return func(o *Options) error {
o.WithRetry = true
return nil
}
}
// WithHeaders - Set headers that will be sent every request.
func WithHeaders(headers map[string]string) FnOpts {
return func(o *Options) error {
o.DefaultHeaders = headers
return nil
}
}
// WithRetryStrategy - set custom retry strategy
func WithRetryStrategy(strategy *[]time.Duration) FnOpts {
return func(o *Options) error {
o.WithRetry = true
o.RetryStrategy = strategy
return nil
}
}
// WithHTTPClient - set custom http client
func WithHTTPClient(client *http.Client) FnOpts {
return func(o *Options) error {
o.HTTPClient = client
return nil
}
}
// setDefaultRetryStrategy - sets the retry attempts
func setDefaultRetryStrategy() []time.Duration {
return []time.Duration{
1 * time.Second,
3 * time.Second,
5 * time.Second,
10 * time.Second,
}
}
// setDefaultClient - returns the default http client
func setDefaultClient() *http.Client {
return &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 15 * time.Second,
KeepAlive: 15 * time.Second,
}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 10,
IdleConnTimeout: 30 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
Timeout: time.Second * 15,
}
}
func setDefaultFetch() *Client {
return &Client{
RetryStrategy: setDefaultRetryStrategy(),
Client: setDefaultClient(),
}
}