Using a Proxy in Custom Transport: Go Programmatic Solution
In Go, by default, the http.Client uses the system's proxy settings as configured in environment variables like HTTP_PROXY and HTTPS_PROXY. However, this behavior may not extend to custom transports.
Using http.ProxyFromEnvironment to Set Proxy
To programmatically configure a proxy for a custom transport, you can use the http.ProxyFromEnvironment method. This method returns a proxy URL based on the environment variables, with HTTPS_PROXY taking precedence for HTTPS requests.
<code class="go">import ( "log" "net/http" "os" ) func main() { // Get proxy URL from environment variables proxyURL := http.ProxyFromEnvironment(os.Getenv) // Create a custom transport transport := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, Proxy: proxyURL, } // Create a client with the custom transport client := &http.Client{Transport: transport} // Send a request through the proxy resp, err := client.Get("https://example.com") if err != nil { log.Fatal("Error making request:", err) } // Read the response body defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal("Error reading response:", err) } // Print the response body fmt.Println(string(body)) }</code>
This code snippet demonstrates the use of http.ProxyFromEnvironment to set the proxy for a custom transport. By using environment variables to configure the proxy settings, you can easily switch between different proxy configurations without modifying the code.
The above is the detailed content of How do I Programmatically Configure a Proxy for a Custom Transport in Go?. For more information, please follow other related articles on the PHP Chinese website!