Home >Backend Development >Golang >How to Override the Source IP Address for HTTP Requests in Go?
Overriding IP Address for HTTP Requests in Go
In Go, the net/http package facilitates HTTP requests using the default IP address of the system. However, there are instances where you may prefer to specify a custom IP address for such requests. This article demonstrates how to achieve this using Dialer configuration.
The challenge stems from the absence of documentation regarding the current address used by the http library. To specify the source address for an HTTP request, we must customize the Dialer in the Client's Transport.
Here is how it's done:
// Establish a transport similar to http.DefaultTransport, but with a custom local address transport := &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, LocalAddr: localAddr, // Specify the desired local IP address 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 configuring the Dialer in this manner, the LocalAddr parameter specifies the custom IP address that will be used as the source address for all HTTP requests made by the client.
The above is the detailed content of How to Override the Source IP Address for HTTP Requests in Go?. For more information, please follow other related articles on the PHP Chinese website!