How do I Programmatically Configure a Proxy for a Custom Transport in Go?

Linda Hamilton
Release: 2024-10-26 04:34:30
Original
558 people have browsed it

How do I Programmatically Configure a Proxy for a Custom Transport in Go?

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

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!

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!