Home  >  Article  >  Backend Development  >  How do I Programmatically Configure a Proxy for a Custom Transport in Go?

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 04:34:30559browse

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>

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!

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