In situations where you prefer to avoid using your primary IP address for HTTP requests, Go provides a way to specify the source address.
To achieve this, you can create a custom Dialer within the client's Transport. This is accomplished as follows:
// Create a transport based on http.DefaultTransport, but with a custom localAddr transport := &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, LocalAddr: localAddr, // Set the desired local IP address here DualStack: true, }).DialContext, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, } // Create an HTTP client using the custom transport client := &http.Client{ Transport: transport, }
By setting the LocalAddr field of the Dialer, you can specify the source IP address to be used for HTTP requests made by the client.
The above is the detailed content of How to Customize the Source IP Address for HTTP Requests in Go?. For more information, please follow other related articles on the PHP Chinese website!