Fix "Fix HTTP server leak"

This commit is contained in:
世界 2023-11-24 19:45:43 +08:00
parent 5b9d6eba38
commit e50e7ae2d3
No known key found for this signature in database
GPG key ID: CD109927C34A63C4

View file

@ -21,6 +21,7 @@ import (
type Handler = N.TCPConnectionHandler
func HandleConnection(ctx context.Context, conn net.Conn, reader *std_bufio.Reader, authenticator auth.Authenticator, handler Handler, metadata M.Metadata) error {
var httpClient *http.Client
for {
request, err := ReadRequest(reader)
if err != nil {
@ -94,7 +95,8 @@ func HandleConnection(ctx context.Context, conn net.Conn, reader *std_bufio.Read
}
var innerErr error
httpClient := &http.Client{
if httpClient == nil {
httpClient = &http.Client{
Transport: &http.Transport{
DisableCompression: true,
DialContext: func(context context.Context, network, address string) (net.Conn, error) {
@ -115,9 +117,11 @@ func HandleConnection(ctx context.Context, conn net.Conn, reader *std_bufio.Read
return http.ErrUseLastResponse
},
}
response, err := httpClient.Do(request)
}
requestCtx, cancel := context.WithCancel(ctx)
response, err := httpClient.Do(request.WithContext(requestCtx))
if err != nil {
cancel()
return E.Errors(innerErr, err, responseWith(request, http.StatusBadGateway).Write(conn))
}
@ -133,10 +137,11 @@ func HandleConnection(ctx context.Context, conn net.Conn, reader *std_bufio.Read
err = response.Write(conn)
if err != nil {
cancel()
return E.Errors(innerErr, err)
}
httpClient.CloseIdleConnections()
cancel()
if !keepAlive {
return conn.Close()