Binding an http.Client to an IP Address in Go
In the realm of distributed computing, it's often necessary to control the source IP address from which HTTP requests originate. With multiple NICs on a client machine, this granularity can be essential.
Consider the following basic HTTP client code:
<code class="go">package main import "net/http" func main() { webclient := &http.Client{} req, _ := http.NewRequest("GET", "http://www.google.com", nil) httpResponse, _ := webclient.Do(req) defer httpResponse.Body.Close() }</code>
To bind this client to a specific NIC or IP address, we need to modify its Transport field. We'll use a custom net.Transport that employs a custom net.Dialer. The net.Dialer, in turn, allows us to specify the local address for outgoing connections.
<code class="go">import ( "net" "net/http" ) func main() { localAddr, err := net.ResolveIPAddr("ip", "<my local address>") if err != nil { panic(err) } localTCPAddr := net.TCPAddr{ IP: localAddr.IP, } webclient := &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{LocalAddr: &localTCPAddr}).DialContext, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, }, } }</code>
With this modification, our HTTP client is now bound to the specified IP address, ensuring that all outgoing requests originate from the desired NIC.
The above is the detailed content of How Can I Bind a Go HTTP Client to a Specific IP Address?. For more information, please follow other related articles on the PHP Chinese website!