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

How to configure Go programs to utilize a custom proxy?

Linda Hamilton
Release: 2024-10-26 08:45:30
Original
971 people have browsed it

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

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

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

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

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!

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