|
1 | 1 | package httpx
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "net" |
4 | 5 | "net/http"
|
| 6 | + "runtime" |
5 | 7 | "time"
|
6 | 8 | )
|
7 | 9 |
|
8 |
| -// Doer is an interface for http.Client. |
9 |
| -type Doer interface { |
| 10 | +// Doer is a backward compatible definition for [Client]. |
| 11 | +type Doer = Client |
| 12 | + |
| 13 | +// Client is an interface for [http.Client]. |
| 14 | +type Client interface { |
10 | 15 | Do(req *http.Request) (*http.Response, error)
|
11 | 16 | }
|
12 | 17 |
|
13 |
| -// NewClient return http.Client with a sane default. |
| 18 | +// NewClient returns [http.Client] with a sane defaults and non-shared [http.Transport]. |
| 19 | +// See [NewTransport] for more info. |
14 | 20 | func NewClient() *http.Client {
|
15 | 21 | return &http.Client{
|
16 |
| - Timeout: 5 * time.Second, |
| 22 | + Transport: NewTransport(), |
| 23 | + Timeout: 5 * time.Second, |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +// NewPooledClient returns [http.Client] which will be used for the same host(s). |
| 28 | +func NewPooledClient() *http.Client { |
| 29 | + return &http.Client{ |
| 30 | + Transport: NewPooledTransport(), |
| 31 | + Timeout: 5 * time.Second, |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +// NewTransport returns [http.Transport] with idle connections and keepalives disabled. |
| 36 | +func NewTransport() *http.Transport { |
| 37 | + transport := NewPooledTransport() |
| 38 | + transport.DisableKeepAlives = true |
| 39 | + transport.MaxIdleConnsPerHost = -1 |
| 40 | + return transport |
| 41 | +} |
| 42 | + |
| 43 | +// NewPooledTransport returns [http.Transport] which will be used for the same host(s). |
| 44 | +func NewPooledTransport() *http.Transport { |
| 45 | + transport := &http.Transport{ |
| 46 | + Proxy: http.ProxyFromEnvironment, |
| 47 | + DialContext: (&net.Dialer{ |
| 48 | + Timeout: 30 * time.Second, |
| 49 | + KeepAlive: 30 * time.Second, |
| 50 | + DualStack: true, |
| 51 | + }).DialContext, |
| 52 | + TLSHandshakeTimeout: 10 * time.Second, |
| 53 | + MaxIdleConns: 100, |
| 54 | + MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1, |
| 55 | + IdleConnTimeout: 90 * time.Second, |
| 56 | + ExpectContinueTimeout: 1 * time.Second, |
| 57 | + ForceAttemptHTTP2: true, |
17 | 58 | }
|
| 59 | + return transport |
18 | 60 | }
|
0 commit comments