How to set which IP address to use for an HTTP request?

I don't know if this is possible, since std lib does not indicate anything about the current address that is being used:

http://golang.org/pkg/net/http/

resp, err := http.Get("http://example.com/") if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) 

What I'm trying to do is set the source address for this HTTP request, why? because I don’t want to use my primary IP address for this kind of thing ...

+7
go
source share
1 answer

You can install a custom Dialer in Client Transport.

 // Create a transport like http.DefaultTransport, but with a specified localAddr transport := &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, LocalAddr: localAddr, DualStack: true, }).DialContext, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, } client := &http.Client{ Transport: transport, } 
+17
source

All Articles