-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttpclient.go
74 lines (64 loc) · 1.96 KB
/
httpclient.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Package httpclient adds support for resettable read/write timeouts to Go's HTTP transport and exposes
// a not shared HTTP client with sensible timeouts.
package httpclient
import (
"context"
"net"
"net/http"
"time"
)
// DialContextFn was defined to make code more readable.
type DialContextFn func(ctx context.Context, network, address string) (net.Conn, error)
// DialContext implements our own dialer in order to set read and write idle timeouts.
func DialContext(rwtimeout, ctimeout time.Duration) DialContextFn {
dialer := &net.Dialer{Timeout: ctimeout}
return func(ctx context.Context, network, addr string) (net.Conn, error) {
c, err := dialer.DialContext(ctx, network, addr)
if err != nil {
return nil, err
}
if rwtimeout > 0 {
timeoutConn := &tcpConn{
TCPConn: c.(*net.TCPConn),
timeout: rwtimeout,
}
return timeoutConn, nil
}
return c, nil
}
}
// tcpConn is our own net.Conn which sets a read and write deadline and resets them each
// time there is read or write activity in the connection.
type tcpConn struct {
*net.TCPConn
timeout time.Duration
}
func (c *tcpConn) Read(b []byte) (int, error) {
err := c.TCPConn.SetDeadline(time.Now().Add(c.timeout))
if err != nil {
return 0, err
}
return c.TCPConn.Read(b)
}
func (c *tcpConn) Write(b []byte) (int, error) {
err := c.TCPConn.SetDeadline(time.Now().Add(c.timeout))
if err != nil {
return 0, err
}
return c.TCPConn.Write(b)
}
// Default returns a default HTTP client with sensible values for slow 3G connections and above.
func Default() *http.Client {
return &http.Client{
Transport: &http.Transport{
DialContext: DialContext(30*time.Second, 10*time.Second),
ForceAttemptHTTP2: true,
Proxy: http.ProxyFromEnvironment,
MaxIdleConns: 100,
IdleConnTimeout: 30 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
},
}
}