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

Susan Sarandon
Release: 2024-10-26 05:22:30
Original
233 people have browsed it

##  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>
Copy after login

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'
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!