]>
Commit | Line | Data |
---|---|---|
9b12e4fe JC |
1 | package cleanhttp |
2 | ||
3 | import ( | |
4 | "net" | |
5 | "net/http" | |
6 | "runtime" | |
7 | "time" | |
8 | ) | |
9 | ||
10 | // DefaultTransport returns a new http.Transport with the same default values | |
11 | // as http.DefaultTransport | |
12 | func DefaultTransport() *http.Transport { | |
13 | transport := &http.Transport{ | |
14 | Proxy: http.ProxyFromEnvironment, | |
15 | Dial: (&net.Dialer{ | |
16 | Timeout: 30 * time.Second, | |
17 | KeepAlive: 30 * time.Second, | |
18 | }).Dial, | |
19 | TLSHandshakeTimeout: 10 * time.Second, | |
20 | } | |
21 | SetTransportFinalizer(transport) | |
22 | return transport | |
23 | } | |
24 | ||
25 | // DefaultClient returns a new http.Client with the same default values as | |
26 | // http.Client, but with a non-shared Transport | |
27 | func DefaultClient() *http.Client { | |
28 | return &http.Client{ | |
29 | Transport: DefaultTransport(), | |
30 | } | |
31 | } | |
32 | ||
33 | // SetTransportFinalizer sets a finalizer on the transport to ensure that | |
34 | // idle connections are closed prior to garbage collection; otherwise | |
35 | // these may leak | |
36 | func SetTransportFinalizer(transport *http.Transport) { | |
37 | runtime.SetFinalizer(&transport, func(t **http.Transport) { | |
38 | (*t).CloseIdleConnections() | |
39 | }) | |
40 | } |