Better setting of a custom http.Client
Florin Patan
6 years ago
12 | 12 | "net/url" |
13 | 13 | "os" |
14 | 14 | "path/filepath" |
15 | "strings" | |
15 | 16 | "time" |
16 | 17 | ) |
17 | 18 | |
19 | // HTTPRequester defines the minimal interface needed for an http.Client to be implemented. | |
20 | // | |
21 | // Use it in conjunction with the SetHTTPClient function to allow for other capabilities | |
22 | // like a tracing http.Client | |
23 | type HTTPRequester interface { | |
24 | Do(*http.Request) (*http.Response, error) | |
25 | } | |
26 | ||
27 | var customHTTPClient HTTPRequester | |
28 | ||
29 | // HTTPClient sets a custom http.Client | |
30 | // deprecated: in favor of SetHTTPClient() | |
18 | 31 | var HTTPClient = &http.Client{} |
19 | 32 | |
20 | 33 | type WebResponse struct { |
94 | 107 | if err != nil { |
95 | 108 | return err |
96 | 109 | } |
97 | resp, err := HTTPClient.Do(req) | |
110 | resp, err := getHTTPClient().Do(req) | |
98 | 111 | if err != nil { |
99 | 112 | return err |
100 | 113 | } |
110 | 123 | } |
111 | 124 | |
112 | 125 | func postForm(endpoint string, values url.Values, intf interface{}, debug bool) error { |
113 | resp, err := HTTPClient.PostForm(endpoint, values) | |
126 | reqBody := strings.NewReader(values.Encode()) | |
127 | req, err := http.NewRequest("POST", endpoint, reqBody) | |
128 | if err != nil { | |
129 | return err | |
130 | } | |
131 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") | |
132 | ||
133 | resp, err := getHTTPClient().Do(req) | |
114 | 134 | if err != nil { |
115 | 135 | return err |
116 | 136 | } |
146 | 166 | |
147 | 167 | return nil |
148 | 168 | } |
169 | ||
170 | func getHTTPClient() HTTPRequester { | |
171 | if customHTTPClient != nil { | |
172 | return customHTTPClient | |
173 | } | |
174 | ||
175 | return HTTPClient | |
176 | } | |
177 | ||
178 | // SetHTTPClient allows you to specify a custom http.Client | |
179 | // Use this instead of the package level HTTPClient variable if you want to use a custom client like the | |
180 | // Stackdriver Trace HTTPClient https://godoc.org/cloud.google.com/go/trace#HTTPClient | |
181 | func SetHTTPClient(client HTTPRequester) { | |
182 | customHTTPClient = client | |
183 | } |