forked from dropbox/godropbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_pool.go
157 lines (138 loc) · 4.46 KB
/
simple_pool.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package http2
import (
"crypto/tls"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/dropbox/godropbox/errors"
)
const (
// This is a hax to propagate DialError with the Do call
dialErrorMsgPrefix = "dial "
)
// Pool of persistent HTTP connections. The only limit is on the max # of idle connections we
// cache. Like Python's dropbox.curllib.CurlConnectionPool.
type SimplePool struct {
// no locking needed, because http.Client has its own locking
client *http.Client
transport *http.Transport
addr string
params ConnectionParams
}
// get from http://golang.org/src/pkg/net/http/transport.go
func getenvEitherCase(k string) string {
if v := os.Getenv(strings.ToUpper(k)); v != "" {
return v
}
return os.Getenv(strings.ToLower(k))
}
// Creates a new HTTP connection pool using the given address and pool parameters.
//
// 'addr' is a net.Dial()-style 'host:port' destination for making the TCP connection for
// HTTP/HTTPS traffic. It will be used as the hostname by default for virtual hosting
// and SSL certificate validation; if you'd like to use a different hostname,
// set params.HostHeader.
func NewSimplePool(addr string, params ConnectionParams) *SimplePool {
pool := &SimplePool{
addr: addr,
params: params,
client: new(http.Client),
}
// It's desirable to enforce the timeout at the client-level since it
// includes the connection time, redirects and the time to finish reading
// the full response. Unlike ResponseHeaderTimeout supported by
// `http.Transport` which merely accounts for the timeout to receive the
// first response header byte. It ignores the time to send the request or
// the time to read the full response.
pool.client.Timeout = params.ResponseTimeout
// setup HTTP transport
transport := new(http.Transport)
transport.ResponseHeaderTimeout = params.ResponseTimeout
transport.MaxIdleConnsPerHost = params.MaxIdle
if params.Proxy != nil {
transport.Proxy = params.Proxy
} else {
transport.Proxy = http.ProxyFromEnvironment
}
if params.Dial == nil {
// dialTimeout could only be used in none proxy requests since it talks directly
// to pool.addr
if getenvEitherCase("HTTP_PROXY") == "" && params.Proxy == nil {
transport.Dial = pool.dialTimeout
}
} else {
transport.Dial = params.Dial
}
pool.transport = transport
pool.client.Transport = transport
if params.UseSSL && params.SkipVerifySSL {
transport.TLSClientConfig = &tls.Config{
InsecureSkipVerify: true,
}
}
return pool
}
// Adds connection timeout for HTTP client
//
// Note - we do not use the addr passed in, which golang's http library
// has parsed from the URL, so that we can connect to whatever specific host
// was passed in originally as addr to NewSimplePool().
func (pool *SimplePool) dialTimeout(network, addr string) (net.Conn, error) {
c, err := net.DialTimeout(network, pool.addr, pool.params.ConnectTimeout)
if err == nil {
tcp := c.(*net.TCPConn)
tcp.SetKeepAlive(true)
tcp.SetKeepAlivePeriod(10 * time.Second)
}
return c, err
}
// Performs the HTTP request using our HTTP client
func (pool *SimplePool) Do(req *http.Request) (resp *http.Response, err error) {
conn, err := pool.Get()
if err != nil {
return nil, errors.Wrap(err, err.Error())
}
if pool.params.UseSSL {
req.URL.Scheme = "https"
} else {
req.URL.Scheme = "http"
}
if pool.params.HostHeader != nil {
req.URL.Host = *pool.params.HostHeader
} else {
req.URL.Host = pool.addr
}
// transport.ResponseHeaderTimeout doesn't encompass the time it takes to write the full
// request, thus timeout for reading the body should be handled by the caller who is
// consuming the response.
resp, err = conn.Do(req)
if err != nil {
var isDialError bool
if urlErr, ok := err.(*url.Error); ok {
if strings.HasPrefix(urlErr.Err.Error(), dialErrorMsgPrefix) {
isDialError = true
}
}
if isDialError {
err = DialError{errors.Wrap(err, "SimplePool: Dial Error")}
} else {
err = errors.Wrap(err, err.Error())
}
}
return
}
// Returns the HTTP client, which is thread-safe.
//
// Note that we use http.Client, rather than httputil.ClientConn, despite http.Client being higher-
// level. This is normally a liability for backend code, but it has more robust error handling and
// provides functionality that's more comparable to pycurl/curllib.
func (pool *SimplePool) Get() (*http.Client, error) {
return pool.client, nil
}
// Closes all idle connections in this pool
func (pool *SimplePool) Close() {
pool.transport.CloseIdleConnections()
}