Go: Send websocket requests to a proxy port

Viewed 36

I have an Envoy proxy instance configured to proxy http and websocket requests. Note that this is not a CONNECT proxy. I want my websocket client to create a websocket request as if it was sending it to the original destination and then deliver the payload to the proxy's listener instead.

What's the recommended way to connect to the local proxy? I believe this is dependent on the specific Go websocket package being used. I can see packages that allow overriding the http.Client used, but the destination address is determined using the websocket URL specified. The only alternative I have is to send the request to ws://proxy_ip:proxy_port/path directly, and specify the destination using some custom HTTP header that the proxy is configured to use for routing. I am not a big fan of this approach.

1 Answers

I want to dial an address different from that in the request

Use Gorilla's Dialer.NetDialContext to dial an address different from the request:

d := websocket.Dialer{
    NetDialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
        return net.DialContext(ctx, network, "proxy_ip:proxy_port")
    },
}

c, r, err := d.Dial("ws://example.com/path", nil)
if err != nil {
    // handle error
}
Related