qwatros
qwatros

Reputation: 13

socks5 proxy client with context support

Is it possible to use a context with the Dialer returned by the SOCKS5 function from net/proxy library?

If a SOCKS5 proxy Dialer blocks while establishing the connection, an HTTP client using the proxy Dialer could get stuck without a way to abort the connection.

Upvotes: 0

Views: 1518

Answers (1)

leaf bebop
leaf bebop

Reputation: 8222

Under the hood of golang.org/x/net/proxy.SOCKS5 it uses golang.org/x/net/internal/socks.Dialer, which has an exported method DialContext, and since Go 1.7, http.Transport supports a custom DialContext as a field. So you can cast the dialer to an interface with method DialContext and set it to a custom transport.

dc := dialer.(interface {
    DialContext(ctx context.Context, network, addr string) (net.Conn, error)
})
httpTransport.DialContext = dc.DialContext

playground: https://play.golang.org/p/tSi9IZ-2Zqg

Note: while this is valid Go code, some would argue it relies on implementation details that the package does not want to export (hidden in internal). I think it is best to send an issue to Go team to ask for export it; if it is too much an issue for you, you can either copy the code and preserve it from changing, or use http.Client.Timeout or write start every http.Do concurrently and wraps a select over it for context like dealing with any blocking operation.

Upvotes: 1

Related Questions