Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions cleanhttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
// DefaultTransport returns a new http.Transport with similar default values to
// http.DefaultTransport, but with idle connections and keepalives disabled.
func DefaultTransport() *http.Transport {
transport := DefaultPooledTransport()
transport := DefaultPooledTransportWithMin(0)
transport.DisableKeepAlives = true
transport.MaxIdleConnsPerHost = -1
return transport
Expand All @@ -24,6 +24,14 @@ func DefaultTransport() *http.Transport {
// it can leak file descriptors over time. Only use this for transports that
// will be re-used for the same host(s).
func DefaultPooledTransport() *http.Transport {
return DefaultPooledTransportWithMin(0)
}

// DefaultPooledTransportWithMin returns a new http.Transport with a minimum
// value for MaxIdleConnsPerHost. Do not use this for transient transports as
// it can leak file descriptors over time. Only use this for transports that
// will be re-used for the same host(s).
func DefaultPooledTransportWithMin(minIdleConnsPerHost int) *http.Transport {
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Expand All @@ -36,7 +44,13 @@ func DefaultPooledTransport() *http.Transport {
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
ForceAttemptHTTP2: true,
MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1,
MaxIdleConnsPerHost: func() int {
maxIdleConnsPerHost := runtime.GOMAXPROCS(0) + 1
if maxIdleConnsPerHost < minIdleConnsPerHost {
return minIdleConnsPerHost
}
return maxIdleConnsPerHost
}(),
}
return transport
}
Expand All @@ -55,7 +69,15 @@ func DefaultClient() *http.Client {
// transient clients as it can leak file descriptors over time. Only use this
// for clients that will be re-used for the same host(s).
func DefaultPooledClient() *http.Client {
return DefaultPooledClientWithMin(0)
}

// DefaultPooledClient returns a new http.Client with similar default values to
// http.Client, but with a shared Transport and minimum value for MaxIdleConnsPerHost.
// Do not use this function for transient clients as it can leak file descriptors
// over time. Only use this for clients that will be re-used for the same host(s).
func DefaultPooledClientWithMin(minIdleConnsPerHost int) *http.Client {
return &http.Client{
Transport: DefaultPooledTransport(),
Transport: DefaultPooledTransportWithMin(minIdleConnsPerHost),
}
}