Add ability to override proxy from environment in http response (#3626)

This commit is contained in:
Marcel 2018-03-06 21:11:38 +01:00 committed by Daniel Nelson
parent 8fac10e3e5
commit 1a03db7119
1 changed files with 21 additions and 1 deletions

View File

@ -20,6 +20,7 @@ import (
// HTTPResponse struct // HTTPResponse struct
type HTTPResponse struct { type HTTPResponse struct {
Address string Address string
Proxy string
Body string Body string
Method string Method string
ResponseTimeout internal.Duration ResponseTimeout internal.Duration
@ -49,6 +50,9 @@ var sampleConfig = `
## Server address (default http://localhost) ## Server address (default http://localhost)
# address = "http://localhost" # address = "http://localhost"
## Set http_proxy (telegraf uses the system wide proxy settings if it's is not set)
# http_proxy = "http://localhost:8888"
## Set response_timeout (default 5 seconds) ## Set response_timeout (default 5 seconds)
# response_timeout = "5s" # response_timeout = "5s"
@ -88,6 +92,22 @@ func (h *HTTPResponse) SampleConfig() string {
// ErrRedirectAttempted indicates that a redirect occurred // ErrRedirectAttempted indicates that a redirect occurred
var ErrRedirectAttempted = errors.New("redirect") var ErrRedirectAttempted = errors.New("redirect")
// Set the proxy. A configured proxy overwrites the system wide proxy.
func getProxyFunc(http_proxy string) func(*http.Request) (*url.URL, error) {
if http_proxy == "" {
return http.ProxyFromEnvironment
}
proxyURL, err := url.Parse(http_proxy)
if err != nil {
return func(_ *http.Request) (*url.URL, error) {
return nil, errors.New("bad proxy: " + err.Error())
}
}
return func(r *http.Request) (*url.URL, error) {
return proxyURL, nil
}
}
// CreateHttpClient creates an http client which will timeout at the specified // CreateHttpClient creates an http client which will timeout at the specified
// timeout period and can follow redirects if specified // timeout period and can follow redirects if specified
func (h *HTTPResponse) createHttpClient() (*http.Client, error) { func (h *HTTPResponse) createHttpClient() (*http.Client, error) {
@ -98,7 +118,7 @@ func (h *HTTPResponse) createHttpClient() (*http.Client, error) {
} }
client := &http.Client{ client := &http.Client{
Transport: &http.Transport{ Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment, Proxy: getProxyFunc(h.Proxy),
DisableKeepAlives: true, DisableKeepAlives: true,
TLSClientConfig: tlsCfg, TLSClientConfig: tlsCfg,
}, },