Skip to content

Commit 72c3834

Browse files
committed
Allow passing minimum value for MaxIdleConnsPerHost
1 parent 078f815 commit 72c3834

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

cleanhttp.go

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import (
1313
// DefaultTransport returns a new http.Transport with similar default values to
1414
// http.DefaultTransport, but with idle connections and keepalives disabled.
1515
func DefaultTransport() *http.Transport {
16-
transport := DefaultPooledTransport()
16+
transport := DefaultPooledTransportWithMin(0)
1717
transport.DisableKeepAlives = true
1818
transport.MaxIdleConnsPerHost = -1
1919
return transport
@@ -24,6 +24,14 @@ func DefaultTransport() *http.Transport {
2424
// it can leak file descriptors over time. Only use this for transports that
2525
// will be re-used for the same host(s).
2626
func DefaultPooledTransport() *http.Transport {
27+
return DefaultPooledTransportWithMin(0)
28+
}
29+
30+
// DefaultPooledTransportWithMin returns a new http.Transport with a minimum
31+
// value for MaxIdleConnsPerHost. Do not use this for transient transports as
32+
// it can leak file descriptors over time. Only use this for transports that
33+
// will be re-used for the same host(s).
34+
func DefaultPooledTransportWithMin(minIdleConnsPerHost int) *http.Transport {
2735
transport := &http.Transport{
2836
Proxy: http.ProxyFromEnvironment,
2937
DialContext: (&net.Dialer{
@@ -36,7 +44,13 @@ func DefaultPooledTransport() *http.Transport {
3644
TLSHandshakeTimeout: 10 * time.Second,
3745
ExpectContinueTimeout: 1 * time.Second,
3846
ForceAttemptHTTP2: true,
39-
MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1,
47+
MaxIdleConnsPerHost: func() int {
48+
maxIdleConnsPerHost := runtime.GOMAXPROCS(0) + 1
49+
if maxIdleConnsPerHost < minIdleConnsPerHost {
50+
return minIdleConnsPerHost
51+
}
52+
return maxIdleConnsPerHost
53+
}(),
4054
}
4155
return transport
4256
}
@@ -55,7 +69,15 @@ func DefaultClient() *http.Client {
5569
// transient clients as it can leak file descriptors over time. Only use this
5670
// for clients that will be re-used for the same host(s).
5771
func DefaultPooledClient() *http.Client {
72+
return DefaultPooledClientWithMin(0)
73+
}
74+
75+
// DefaultPooledClient returns a new http.Client with similar default values to
76+
// http.Client, but with a shared Transport and minimum value for MaxIdleConnsPerHost.
77+
// Do not use this function for transient clients as it can leak file descriptors
78+
// over time. Only use this for clients that will be re-used for the same host(s).
79+
func DefaultPooledClientWithMin(minIdleConnsPerHost int) *http.Client {
5880
return &http.Client{
59-
Transport: DefaultPooledTransport(),
81+
Transport: DefaultPooledTransportWithMin(minIdleConnsPerHost),
6082
}
6183
}

0 commit comments

Comments
 (0)