doq13207 2018-08-14 16:12
浏览 88
已采纳

使用自定义传输时,如何编程去使用代理?

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条回答 默认 最新

  • doufunuo4787 2018-11-08 07:02
    关注

    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 
    ", string(bodyString))
    
    
    }

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100