Home >Backend Development >Golang >How Can I Configure a Go HTTP Client to Use a Proxy Server?
Using a proxy server with an HTTP client can enhance privacy or enable access to restricted resources. Go provides multiple methods to establish a proxy configuration for HTTP requests.
Lukas's suggestion is straightforward. Setting the HTTP_PROXY environment variable to the desired proxy address (e.g., "http://proxyIp:proxyPort") will cause Go's HTTP client to automatically use that proxy.
Bash:
export HTTP_PROXY="http://proxyIp:proxyPort"
Go:
os.Setenv("HTTP_PROXY", "http://proxyIp:proxyPort")
For cases where the environment variable cannot be modified or cannot be relied upon, a custom HTTP client with a designated proxy can be created:
proxyUrl, err := url.Parse("http://proxyIp:proxyPort") myClient := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyUrl)}}
This approach affects the gesamten program, ensuring that all HTTP requests use the specified proxy:
proxyUrl, err := url.Parse("http://proxyIp:proxyPort") http.DefaultTransport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)}
The above is the detailed content of How Can I Configure a Go HTTP Client to Use a Proxy Server?. For more information, please follow other related articles on the PHP Chinese website!