Configuring Proxy for HTTP Client in Go
When working with HTTP clients, it's often necessary to set up a proxy to manage network traffic. However, navigating the documentation can be confusing, as specific proxy-related functions may not be readily apparent.
HTTP_PROXY Environment Variable
One straightforward approach is to set the HTTP_PROXY environment variable. This will instruct Go to use the specified proxy by default:
export HTTP_PROXY="http://proxyIp:proxyPort"
os.Setenv("HTTP_PROXY", "http://proxyIp:proxyPort")
Custom HTTP Client
Alternatively, you can create a custom http.Client that explicitly uses a proxy:
proxyUrl, err := url.Parse("http://proxyIp:proxyPort") myClient := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyUrl)}}
This method is useful when you cannot rely on environment configuration or prefer not to modify it.
Default Transport Modification
Lastly, you can modify the default transport used by the net/http package, affecting all HTTP clients in your program:
proxyUrl, err := url.Parse("http://proxyIp:proxyPort") http.DefaultTransport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)}
The above is the detailed content of How to Configure a Proxy for HTTP Clients in Go?. For more information, please follow other related articles on the PHP Chinese website!