From 135247b908c5584408ebf81fb8ae27be21dd6f88 Mon Sep 17 00:00:00 2001 From: Joel Diaz Date: Sun, 26 Mar 2023 10:02:11 -0400 Subject: [PATCH] =?UTF-8?q?=E2=AD=90=EF=B8=8F=20manual=20client=20creation?= =?UTF-8?q?=20(with=20proxy)=20(#25)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * manual client creation (with proxy) Keep DefaultHttpClient() the way it is, but introduce a new HttpClient() that will allow specifying non-default values for the client. Specifically, allow passing in a proxy string that will used for connections. Signed-off-by: Joel Diaz --- httpclient.go | 45 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/httpclient.go b/httpclient.go index 4a0c718..325ef68 100644 --- a/httpclient.go +++ b/httpclient.go @@ -3,6 +3,7 @@ package ranger import ( "net" "net/http" + "net/url" "time" ) @@ -12,9 +13,14 @@ var ( DefaultTLSHandshakeTimeout = 10 * time.Second ) -func DefaultHttpClient() *http.Client { +func newHttpTransport(proxy *url.URL) *http.Transport { + proxyFn := http.ProxyFromEnvironment + if proxy != nil { + proxyFn = http.ProxyURL(proxy) + } + tr := &http.Transport{ - Proxy: http.ProxyFromEnvironment, + Proxy: proxyFn, DialContext: (&net.Dialer{ Timeout: DefaultHttpTimeout, KeepAlive: 30 * time.Second, @@ -25,9 +31,40 @@ func DefaultHttpClient() *http.Client { ExpectContinueTimeout: 1 * time.Second, } - httpClient := &http.Client{ + return tr +} + +func newHttpClient(tr *http.Transport) *http.Client { + return &http.Client{ Transport: tr, Timeout: DefaultHttpTimeout, } - return httpClient +} + +// DefaultHttpClient will set up a basic client +// with default timeouts/proxies/etc. +func DefaultHttpClient() *http.Client { + tr := newHttpTransport(nil) + + return newHttpClient(tr) +} + +type HttpClientOpts struct { + // Proxy is the string representation of the proxy the client + // should use for connections. + Proxy string +} + +func NewHttpClient(opts *HttpClientOpts) (*http.Client, error) { + var proxy *url.URL + if opts.Proxy != "" { + var err error + proxy, err = url.Parse(opts.Proxy) + if err != nil { + return nil, err + } + } + tr := newHttpTransport(proxy) + + return newHttpClient(tr), nil }