...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package client
16
17 import (
18 "net/http"
19
20 "github.com/hashicorp/go-retryablehttp"
21 )
22
23
24 type Option func(*options)
25
26 type options struct {
27 UserAgent string
28 RetryCount uint
29 InsecureTLS bool
30 Logger interface{}
31 }
32
33 const (
34
35 DefaultRetryCount = 3
36 )
37
38 func makeOptions(opts ...Option) *options {
39 o := &options{
40 UserAgent: "",
41 RetryCount: DefaultRetryCount,
42 }
43
44 for _, opt := range opts {
45 opt(o)
46 }
47
48 return o
49 }
50
51
52 func WithUserAgent(userAgent string) Option {
53 return func(o *options) {
54 o.UserAgent = userAgent
55 }
56 }
57
58
59 func WithRetryCount(retryCount uint) Option {
60 return func(o *options) {
61 o.RetryCount = retryCount
62 }
63 }
64
65
66 func WithLogger(logger interface{}) Option {
67 return func(o *options) {
68 switch logger.(type) {
69 case retryablehttp.Logger, retryablehttp.LeveledLogger:
70 o.Logger = logger
71 }
72 }
73 }
74
75 func WithInsecureTLS(enabled bool) Option {
76 return func(o *options) {
77 o.InsecureTLS = enabled
78 }
79 }
80
81 type roundTripper struct {
82 http.RoundTripper
83 UserAgent string
84 }
85
86
87 func (rt *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
88 req.Header.Set("User-Agent", rt.UserAgent)
89 return rt.RoundTripper.RoundTrip(req)
90 }
91
92 func createRoundTripper(inner http.RoundTripper, o *options) http.RoundTripper {
93 if inner == nil {
94 inner = http.DefaultTransport
95 }
96 if o.UserAgent == "" {
97
98 return inner
99 }
100 return &roundTripper{
101 RoundTripper: inner,
102 UserAgent: o.UserAgent,
103 }
104 }
105
View as plain text