Home >Backend Development >Golang >How Can I Configure a Go HTTP Client to Use a Proxy Server?

How Can I Configure a Go HTTP Client to Use a Proxy Server?

Barbara Streisand
Barbara StreisandOriginal
2024-12-17 06:14:24132browse

How Can I Configure a Go HTTP Client to Use a Proxy Server?

Setting Up Proxy for HTTP Client

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.

Using HTTP_PROXY Environment Variable

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")

Constructing a Custom HTTP Client with Proxy

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)}}

Modifying the Default HTTP Transport

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn