Home  >  Article  >  Backend Development  >  ## How to Set Up Proxy Support in Go HTTP Clients with Custom Transports?

## How to Set Up Proxy Support in Go HTTP Clients with Custom Transports?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 05:22:30229browse

##  How to Set Up Proxy Support in Go HTTP Clients with Custom Transports?

Using a Proxy in Go Programs with Custom Transports

When creating HTTP clients in Go, it's often necessary to specify a custom transport to handle specific network settings. However, the standard HTTP client doesn't automatically respect the proxy environment variables.

Using http.ProxyFromEnvironment

To enable proxy support in your Go programs, you can use the http.ProxyFromEnvironment method. This method returns a proxy URL based on the environment variables HTTP_PROXY, HTTPS_PROXY, and NO_PROXY.

<code class="go">var PTransport = &http.Transport{
    Proxy: http.ProxyFromEnvironment,
}

client := http.Client{
    Transport: PTransport,
}</code>

Example Usage

To test if this approach works, you can manually set the proxy environment variables:

export http_proxy='http://user:password@proxy-server:3128'
export https_proxy='http://user:password@proxy-server:3128'
export HTTP_PROXY='http://user:password@proxy-server:3128'
export HTTPS_PROXY='http://user:password@proxy-server:3128'

Now, you can create an HTTP client and send a request:

<code class="go">req, _ := http.NewRequest("GET", "https://jsonplaceholder.typicode.com/todos/1", nil)
req.Header.Add("If-None-Match", `some value`)
resp, _ := client.Do(req)</code>

If the proxy settings are correct, the response from the remote server should be displayed.

The above is the detailed content of ## How to Set Up Proxy Support in Go HTTP Clients with Custom Transports?. 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