|
| 1 | +package httputil |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/tls" |
| 5 | + "net/http" |
| 6 | + "time" |
| 7 | +) |
| 8 | + |
| 9 | +const ( |
| 10 | + defaultTimeout = 120 * time.Second |
| 11 | + // defaults to match DefaultTransport - defined to satisfy lint |
| 12 | + maxIdleConns = 100 |
| 13 | + idleConnTimeout = 90 * time.Second |
| 14 | + tLSHandshakeTimeout = 10 * time.Second |
| 15 | + expectContinueTimeout = 1 * time.Second |
| 16 | +) |
| 17 | + |
| 18 | +var preventRedirectCheck = func(_ *http.Request, _ []*http.Request) error { |
| 19 | + return http.ErrUseLastResponse // Prevent following redirects |
| 20 | +} |
| 21 | + |
| 22 | +var safeHTTPClient = &http.Client{ |
| 23 | + Transport: http.DefaultTransport, |
| 24 | + Timeout: defaultTimeout, |
| 25 | + CheckRedirect: preventRedirectCheck, |
| 26 | +} |
| 27 | + |
| 28 | +// SafeHTTPClient returns a default http client which has sensible timeouts, won't follow redirects, and enables idle |
| 29 | +// connection pooling. |
| 30 | +func SafeHTTPClient() *http.Client { |
| 31 | + return safeHTTPClient |
| 32 | +} |
| 33 | + |
| 34 | +// SafeHTTPClientWithTLSConfig returns a http client which has sensible timeouts, won't follow redirects, and if |
| 35 | +// specified a http.Transport with the tls.Config provided. |
| 36 | +func SafeHTTPClientWithTLSConfig(cfg *tls.Config) *http.Client { |
| 37 | + if cfg == nil { |
| 38 | + return safeHTTPClient |
| 39 | + } |
| 40 | + return SafeHTTPClientWithTransport(&http.Transport{ |
| 41 | + TLSClientConfig: cfg, |
| 42 | + // config below matches DefaultTransport |
| 43 | + Proxy: http.ProxyFromEnvironment, |
| 44 | + ForceAttemptHTTP2: true, |
| 45 | + MaxIdleConns: maxIdleConns, |
| 46 | + IdleConnTimeout: idleConnTimeout, |
| 47 | + TLSHandshakeTimeout: tLSHandshakeTimeout, |
| 48 | + ExpectContinueTimeout: expectContinueTimeout, |
| 49 | + }) |
| 50 | +} |
| 51 | + |
| 52 | +// SafeHTTPClientWithTransport returns a http client which has sensible timeouts, won't follow redirects, and if |
| 53 | +// specified the provided http.Transport. |
| 54 | +func SafeHTTPClientWithTransport(transport *http.Transport) *http.Client { |
| 55 | + if transport == nil { |
| 56 | + return safeHTTPClient |
| 57 | + } |
| 58 | + return &http.Client{ |
| 59 | + Transport: transport, |
| 60 | + // config below matches our values for safeHttpClient |
| 61 | + Timeout: defaultTimeout, |
| 62 | + CheckRedirect: preventRedirectCheck, |
| 63 | + } |
| 64 | +} |
0 commit comments