Skip to content

Commit

Permalink
⭐️ manual client creation (with proxy) (#25)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
  • Loading branch information
Joel Diaz authored Mar 26, 2023
1 parent c273e6c commit 135247b
Showing 1 changed file with 41 additions and 4 deletions.
45 changes: 41 additions & 4 deletions httpclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package ranger
import (
"net"
"net/http"
"net/url"
"time"
)

Expand All @@ -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,
Expand All @@ -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
}

0 comments on commit 135247b

Please sign in to comment.