Fix h2mux request context

This commit is contained in:
世界 2023-12-31 15:51:48 +08:00
parent f99a0dfe65
commit 6be79e969e
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
2 changed files with 20 additions and 3 deletions

View file

@ -204,10 +204,21 @@ func (s *h2MuxClientSession) OpenContext(ctx context.Context) (net.Conn, error)
Body: pipeInReader, Body: pipeInReader,
URL: &url.URL{Scheme: "https", Host: "localhost"}, URL: &url.URL{Scheme: "https", Host: "localhost"},
} }
request = request.WithContext(ctx) connCtx, cancel := context.WithCancel(context.Background())
conn := newLateHTTPConn(pipeInWriter) request = request.WithContext(connCtx)
conn := newLateHTTPConn(pipeInWriter, cancel)
requestDone := make(chan struct{})
go func() {
select {
case <-requestDone:
return
case <-ctx.Done():
cancel()
}
}()
go func() { go func() {
response, err := s.transport.RoundTrip(request) response, err := s.transport.RoundTrip(request)
close(requestDone)
if err != nil { if err != nil {
conn.setup(nil, err) conn.setup(nil, err)
} else if response.StatusCode != 200 { } else if response.StatusCode != 200 {

View file

@ -1,6 +1,7 @@
package mux package mux
import ( import (
"context"
"io" "io"
"net" "net"
"os" "os"
@ -16,6 +17,7 @@ type httpConn struct {
writer io.Writer writer io.Writer
create chan struct{} create chan struct{}
err error err error
cancel context.CancelFunc
} }
func newHTTPConn(reader io.Reader, writer io.Writer) *httpConn { func newHTTPConn(reader io.Reader, writer io.Writer) *httpConn {
@ -25,10 +27,11 @@ func newHTTPConn(reader io.Reader, writer io.Writer) *httpConn {
} }
} }
func newLateHTTPConn(writer io.Writer) *httpConn { func newLateHTTPConn(writer io.Writer, cancel context.CancelFunc) *httpConn {
return &httpConn{ return &httpConn{
create: make(chan struct{}), create: make(chan struct{}),
writer: writer, writer: writer,
cancel: cancel,
} }
} }
@ -55,6 +58,9 @@ func (c *httpConn) Write(b []byte) (n int, err error) {
} }
func (c *httpConn) Close() error { func (c *httpConn) Close() error {
if c.cancel != nil {
c.cancel()
}
return common.Close(c.reader, c.writer) return common.Close(c.reader, c.writer)
} }