forked from go-openapi/runtime
/
keepalive.go
53 lines (46 loc) · 1.22 KB
/
keepalive.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
package client
import (
"io"
"io/ioutil"
"net/http"
"sync/atomic"
)
// KeepAliveTransport drains the remaining body from a response
// so that go will reuse the TCP connections.
// This is not enabled by default because there are servers where
// the response never gets closed and that would make the code hang forever.
// So instead it's provided as a http client middleware that can be used to override
// any request.
func KeepAliveTransport(rt http.RoundTripper) http.RoundTripper {
return &keepAliveTransport{wrapped: rt}
}
type keepAliveTransport struct {
wrapped http.RoundTripper
}
func (k *keepAliveTransport) RoundTrip(r *http.Request) (*http.Response, error) {
resp, err := k.wrapped.RoundTrip(r)
if err != nil {
return resp, err
}
resp.Body = &drainingReadCloser{rdr: resp.Body}
return resp, nil
}
type drainingReadCloser struct {
rdr io.ReadCloser
seenEOF uint32
}
func (d *drainingReadCloser) Read(p []byte) (n int, err error) {
n, err = d.rdr.Read(p)
if err == io.EOF || n == 0 {
atomic.StoreUint32(&d.seenEOF, 1)
}
return
}
func (d *drainingReadCloser) Close() error {
// drain buffer
if atomic.LoadUint32(&d.seenEOF) != 1 {
//#nosec
io.Copy(ioutil.Discard, d.rdr)
}
return d.rdr.Close()
}