使用自定义传输时,如何编程去使用代理? [英] How to program Go to use a proxy when using a custom transport?

查看:53
本文介绍了使用自定义传输时,如何编程去使用代理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何根据 go get本身支持标准

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

此博客说,

默认情况下,http.Client在处理任何http.Request之前会检查HTTP_PROXY和HTTPS_PROXY变量.

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)

推荐答案

您可以使用 http.ProxyFromEnvironment 方法

You can use http.ProxyFromEnvironment method

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

ProxyFromEnvironment返回用于给定请求的代理的URL,如环境变量HTTP_PROXY,HTTPS_PROXY和NO_PROXY(或其小写版本)所指示.对于HTTPS请求,HTTPS_PROXY优先于HTTP_PROXY.

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


}

这篇关于使用自定义传输时,如何编程去使用代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆