Skip to content

Commit 6be79e9

Browse files
committed
Fix h2mux request context
1 parent f99a0df commit 6be79e9

2 files changed

Lines changed: 20 additions & 3 deletions

File tree

h2mux.go

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -204,10 +204,21 @@ func (s *h2MuxClientSession) OpenContext(ctx context.Context) (net.Conn, error)
204204
Body: pipeInReader,
205205
URL: &url.URL{Scheme: "https", Host: "localhost"},
206206
}
207-
request = request.WithContext(ctx)
208-
conn := newLateHTTPConn(pipeInWriter)
207+
connCtx, cancel := context.WithCancel(context.Background())
208+
request = request.WithContext(connCtx)
209+
conn := newLateHTTPConn(pipeInWriter, cancel)
210+
requestDone := make(chan struct{})
211+
go func() {
212+
select {
213+
case <-requestDone:
214+
return
215+
case <-ctx.Done():
216+
cancel()
217+
}
218+
}()
209219
go func() {
210220
response, err := s.transport.RoundTrip(request)
221+
close(requestDone)
211222
if err != nil {
212223
conn.setup(nil, err)
213224
} else if response.StatusCode != 200 {

h2mux_conn.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package mux
22

33
import (
4+
"context"
45
"io"
56
"net"
67
"os"
@@ -16,6 +17,7 @@ type httpConn struct {
1617
writer io.Writer
1718
create chan struct{}
1819
err error
20+
cancel context.CancelFunc
1921
}
2022

2123
func newHTTPConn(reader io.Reader, writer io.Writer) *httpConn {
@@ -25,10 +27,11 @@ func newHTTPConn(reader io.Reader, writer io.Writer) *httpConn {
2527
}
2628
}
2729

28-
func newLateHTTPConn(writer io.Writer) *httpConn {
30+
func newLateHTTPConn(writer io.Writer, cancel context.CancelFunc) *httpConn {
2931
return &httpConn{
3032
create: make(chan struct{}),
3133
writer: writer,
34+
cancel: cancel,
3235
}
3336
}
3437

@@ -55,6 +58,9 @@ func (c *httpConn) Write(b []byte) (n int, err error) {
5558
}
5659

5760
func (c *httpConn) Close() error {
61+
if c.cancel != nil {
62+
c.cancel()
63+
}
5864
return common.Close(c.reader, c.writer)
5965
}
6066

0 commit comments

Comments
 (0)