How to program Go to use a proxy?

2019-01-29 09:22发布

How to write Go programs that use a proxy automatically according to the proxy environment variables?

The go get itself support the standard proxy environment variables, but i'm talking about the Go program/code itself.

This blog says,

By default http.Client checks the HTTP_PROXY and HTTPS_PROXY variables before processes any http.Request.

I tried it, but it doesn't work for my following code:

tr := &http.Transport{
    TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
resp, err := client.Get(url)

2条回答
家丑人穷心不美
2楼-- · 2019-01-29 09:40

You must set the Transport Proxy field to use a proxy:

tr := &http.Transport{
  Proxy: ProxyFromEnvironment,
  TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}

It's usually best to copy the default transport and set your options in that transport:

tr := *http.DefaultTransport
tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client := &http.Client{Transport: &tr}
resp, err := client.Get(url)

By copying the default transport, you get useful timeout values and other settings.

查看更多
Deceive 欺骗
3楼-- · 2019-01-29 09:41

You can use http.ProxyFromEnvironment method

  var PTransport = & http.Transport { Proxy: http.ProxyFromEnvironment }
  client: = http.Client { Transport: PTransport }

ProxyFromEnvironment returns the URL of the proxy to use for a given request, as indicated by the environment variables HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions thereof). HTTPS_PROXY takes precedence over HTTP_PROXY for https requests.

I have tried below code, it works, Just add in ur proxy details in terminal.

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'

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))


}

查看更多
登录 后发表回答