Package list golang-github-nlopes-slack / 2d81bca
Better setting of a custom http.Client Florin Patan 4 years ago
1 changed file(s) with 37 addition(s) and 2 deletion(s). Raw diff Collapse all Expand all
1212 "net/url"
1313 "os"
1414 "path/filepath"
15 "strings"
1516 "time"
1617 )
1718
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()
1831 var HTTPClient = &http.Client{}
1932
2033 type WebResponse struct {
94107 if err != nil {
95108 return err
96109 }
97 resp, err := HTTPClient.Do(req)
110 resp, err := getHTTPClient().Do(req)
98111 if err != nil {
99112 return err
100113 }
110123 }
111124
112125 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)
114134 if err != nil {
115135 return err
116136 }
146166
147167 return nil
148168 }
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 }