Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions http2/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,12 @@ type Transport struct {
// waiting for their turn.
StrictMaxConcurrentStreams bool

// IdleConnTimeout is the maximum amount of time an idle
// (keep-alive) connection will remain idle before closing
// itself.
// Zero means no limit.
IdleConnTimeout time.Duration

// ReadIdleTimeout is the timeout after which a health check using ping
// frame will be carried out if no frame is received on the connection.
// Note that a ping response will is considered a received frame, so if
Expand Down Expand Up @@ -3142,9 +3148,17 @@ func (rt noDialH2RoundTripper) RoundTrip(req *http.Request) (*http.Response, err
}

func (t *Transport) idleConnTimeout() time.Duration {
// to keep things backwards compatible, we use non-zero values of
// IdleConnTimeout, followed by using the IdleConnTimeout on the underlying
// http1 transport, followed by 0
if t.IdleConnTimeout != 0 {
return t.IdleConnTimeout
}

if t.t1 != nil {
return t.t1.IdleConnTimeout
}

return 0
}

Expand Down
62 changes: 62 additions & 0 deletions http2/transport_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,68 @@ func startH2cServer(t *testing.T) net.Listener {
return l
}

func TestIdleConnTimeout(t *testing.T) {
for _, test := range []struct {
idleConnTimeout time.Duration
wait time.Duration
baseTransport *http.Transport
wantConns int32
}{{
idleConnTimeout: 2 * time.Second,
wait: 1 * time.Second,
baseTransport: nil,
wantConns: 1,
}, {
idleConnTimeout: 1 * time.Second,
wait: 2 * time.Second,
baseTransport: nil,
wantConns: 5,
}, {
idleConnTimeout: 0 * time.Second,
wait: 1 * time.Second,
baseTransport: &http.Transport{
IdleConnTimeout: 2 * time.Second,
},
wantConns: 1,
}} {
var gotConns int32

st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, r.RemoteAddr)
}, optOnlyServer)
defer st.Close()

tr := &Transport{
IdleConnTimeout: test.idleConnTimeout,
TLSClientConfig: tlsConfigInsecure,
}
defer tr.CloseIdleConnections()

for i := 0; i < 5; i++ {
req, _ := http.NewRequest("GET", st.ts.URL, http.NoBody)
trace := &httptrace.ClientTrace{
GotConn: func(connInfo httptrace.GotConnInfo) {
if !connInfo.Reused {
atomic.AddInt32(&gotConns, 1)
}
},
}
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))

_, err := tr.RoundTrip(req)
if err != nil {
t.Fatalf("%v", err)
}

<-time.After(test.wait)
}

if gotConns != test.wantConns {
t.Errorf("incorrect gotConns: %d != %d", gotConns, test.wantConns)
}
}
}

func TestTransportH2c(t *testing.T) {
l := startH2cServer(t)
defer l.Close()
Expand Down