1
0
mirror of https://github.com/golang/go synced 2024-11-12 08:20:22 -07:00

net/http: add Client.CloseIdleConnections

Fixes #26563

Change-Id: I22b0c72d45fab9d3f31fda04da76a8c0b10cd8b6
Reviewed-on: https://go-review.googlesource.com/130115
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Andrew Bonventre <andybons@golang.org>
This commit is contained in:
Brad Fitzpatrick 2018-08-20 21:04:15 +00:00
parent d169a429c5
commit 85a0192b59
2 changed files with 40 additions and 0 deletions

View File

@ -833,6 +833,22 @@ func (c *Client) Head(url string) (resp *Response, err error) {
return c.Do(req)
}
// CloseIdleConnections closes any connections on its Transport which
// were previously connected from previous requests but are now
// sitting idle in a "keep-alive" state. It does not interrupt any
// connections currently in use.
//
// If the Client's Transport does not have a CloseIdleConnections method
// then this method does nothing.
func (c *Client) CloseIdleConnections() {
type closeIdler interface {
CloseIdleConnections()
}
if tr, ok := c.transport().(closeIdler); ok {
tr.CloseIdleConnections()
}
}
// cancelTimerBody is an io.ReadCloser that wraps rc with two features:
// 1) on Read error or close, the stop func is called.
// 2) On Read failure, if reqDidTimeout is true, the error is wrapped and

View File

@ -1888,3 +1888,27 @@ func TestTransportBodyReadError(t *testing.T) {
t.Errorf("close calls = %d; want 1", closeCalls)
}
}
type roundTripperWithoutCloseIdle struct{}
func (roundTripperWithoutCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
type roundTripperWithCloseIdle func() // underlying func is CloseIdleConnections func
func (roundTripperWithCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
func (f roundTripperWithCloseIdle) CloseIdleConnections() { f() }
func TestClientCloseIdleConnections(t *testing.T) {
c := &Client{Transport: roundTripperWithoutCloseIdle{}}
c.CloseIdleConnections() // verify we don't crash at least
closed := false
var tr RoundTripper = roundTripperWithCloseIdle(func() {
closed = true
})
c = &Client{Transport: tr}
c.CloseIdleConnections()
if !closed {
t.Error("not closed")
}
}