Home  >  Article  >  Backend Development  >  How to configure Go programs to utilize a custom proxy?

How to configure Go programs to utilize a custom proxy?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 08:45:30890browse

How to configure Go programs to utilize a custom proxy?

Customizing Proxy Usage in Go Programs

To automatically configure Go programs to utilize a proxy, the http.Client type provides a ProxyFromEnvironment method. This method examines the HTTP_PROXY and HTTPS_PROXY environment variables to determine the appropriate proxy URL.

In the code snippet provided:

<code class="go">tr := &http.Transport{
    TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
resp, err := client.Get(url)</code>

the transport created does not consider proxy settings. To enable proxy usage, utilize the ProxyFromEnvironment method:

<code class="go">var PTransport = &http.Transport{
  Proxy: http.ProxyFromEnvironment,
}
client := http.Client{
  Transport: PTransport,
}</code>

ProxyFromEnvironment returns the proxy URL derived from the environment variables, prioritizing HTTPS_PROXY for HTTPS requests.

To utilize a custom proxy, define the environment variables as follows:

export http_proxy='http://user:password@prox-server:3128'
export https_proxy='http://user:password@prox-server:3128'
export HTTP_PROXY='http://user:password@prox-server:3128'
export HTTPS_PROXY='http://user:password@prox-server:3128'

The provided code sample, which performs a GET request against a remote API, demonstrates the successful integration of proxy settings:

<code class="go">package main

import (
  "fmt"
  "net/http"
  "io/ioutil"
)

func main() {

  var PTransport = & http.Transport {
    Proxy: http.ProxyFromEnvironment
  }
  client: = http.Client {
    Transport: PTransport
  }
  req, err: = http.NewRequest("GET", "https://jsonplaceholder.typicode.com/todos/1", nil)
  req.Header.Add("If-None-Match", `some value`)
  resp, err: = client.Do(req)
  if err != nil {
    panic(err)
  }
  defer resp.Body.Close()

  bodyBytes, err: = ioutil.ReadAll(resp.Body)
  if err != nil {
    panic(err)
  }

  bodyString: = string(bodyBytes)
  fmt.Printf("GET Response = %s \n", string(bodyString))


}</code>

The above is the detailed content of How to configure Go programs to utilize a custom proxy?. 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