Reuse connection from http.RoundTripper?

I’m trying to proxy an HTTP request that may require websockets. If we get an Upgrade header in the response to upgrade to websockets, we dial a websocket connection. The problem is that this creates two connections to the upstream, which apparently expects the upgrade to happen in the same connection as the initial request. But as far as I can tell, http.RoundTripper (http.Transport) doesn’t provide a way to reuse the first connection.

Here’s the relevant code:

res, err := transport.RoundTrip(outreq)
if err != nil {
	return err
}

if res.StatusCode == http.StatusSwitchingProtocols && strings.ToLower(res.Header.Get("Upgrade")) == "websocket" {
	res.Body.Close()
	hj, ok := rw.(http.Hijacker)
	if !ok {
		return nil
	}
	conn, _, err := hj.Hijack()
	if err != nil {
		return err
	}
	defer conn.Close()
	backendConn, err := net.Dial("tcp", outreq.URL.Host)
	if err != nil {
		return err
	}
	defer backendConn.Close()
	outreq.Write(backendConn)
	// ... the rest is just a concurrent io.Copy()
}

As you can see, we net.Dial a new connection because I don’t know a way to reuse the connection from the RoundTrip() earlier. Is there a better way to do this so that we can reuse that connection?

(To clarify, you don’t have to write code for me, I’m mostly asking about strategy.)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.