Home >Backend Development >Golang >How to Use a Proxy with a Custom Transport in Go?
Program Go for Proxy Usage with Custom Transport
In Go, you can configure the standard library's http.Client to automatically use a proxy based on environment variables. However, when using a custom transport, this functionality is not directly supported.
The solution is to utilize the http.ProxyFromEnvironment method. This method returns the proxy URL to use for a given request based on environment variables such as HTTP_PROXY and HTTPS_PROXY.
To use a proxy with a custom transport in Go, follow these steps:
Create a custom http.Transport instance:
<code class="go">tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }</code>
Set the proxy URL using ProxyFromEnvironment:
<code class="go">var PTransport = &http.Transport{Proxy: http.ProxyFromEnvironment}</code>
Create a http.Client with the custom transport:
<code class="go">client := http.Client{Transport: PTransport}</code>
Use the client to make requests:
<code class="go">resp, err := client.Get(url)</code>
Here's a code example demonstrating this approach:
<code class="go">package main import ( "fmt" "io/ioutil" "net/http" ) func main() { var PTransport = &http.Transport{Proxy: http.ProxyFromEnvironment} client := http.Client{Transport: PTransport} resp, err := client.Get("https://jsonplaceholder.typicode.com/todos/1") if err != nil { panic(err) } bodyBytes, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } fmt.Printf("GET Response = %s \n", string(bodyBytes)) }</code>
Remember to set the HTTP_PROXY and HTTPS_PROXY environment variables appropriately for your proxy server.
The above is the detailed content of How to Use a Proxy with a Custom Transport in Go?. For more information, please follow other related articles on the PHP Chinese website!