为HTTP客户端设置代理 [英] Setting up proxy for HTTP client

查看:1124
本文介绍了为HTTP客户端设置代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置HTTP客户端,以便它使用代理,但是我无法完全理解如何执行此操作。该文档有多个引用代理,但没有任何功能似乎允许定义代理。我需要的是这样的:

  client:=& http.Client {} 
client.SetProxy someip:someport)//伪代码
resp,err:= client.Get(http://example.com)//通过代理请求

任何想法如何在Go中做到这一点?

解决方案

< lukad是正确的,你可以设置 HTTP_PROXY 环境变量,如果你这样做,Go会默认使用它。



bash:

  export HTTP_PROXY =http:// proxyIp:proxyPort
  os.Setenv( HTTP_PROXY,http:// proxyIp:proxyPort)

您也可以构建自己的http .Client必须使用代理而不管环境的配置如何:

  proxyUrl,err:= url.Parse(http:/ / proxyIp:proxyPort)
myClient:=& http.Client {Transport:& http.Transport {Proxy:http.ProxyURL(p roxyUrl)}}

如果您不能依赖环境的配置或不想要修改它。



您也可以修改 net / http 包使用的默认传输。这会影响您的整个程序(包括默认的HTTP客户端)。

  proxyUrl,err:= url.Parse(http: // proxyIp:proxyPort)
http.DefaultTransport =& http.Transport {Proxy:http.ProxyURL(proxyUrl)}


I'm trying to setup the HTTP client so that it uses a proxy, however I cannot quite understand how to do it. The documentation has multiple reference to "proxy" but none of the functions seem to allow to define the proxy. What I need is something like this:

client := &http.Client{}
client.SetProxy("someip:someport") // pseudo code
resp, err := client.Get("http://example.com") // do request through proxy

Any idea how to do this in Go?

解决方案

lukad is correct, you could set the HTTP_PROXY environment variable, if you do this Go will use it by default.

Bash:

export HTTP_PROXY="http://proxyIp:proxyPort"

Go:

os.Setenv("HTTP_PROXY", "http://proxyIp:proxyPort")

You could also construct your own http.Client that MUST use a proxy regardless of the environment's configuration:

proxyUrl, err := url.Parse("http://proxyIp:proxyPort")
myClient := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyUrl)}}

This is useful if you can not depend on the environment's configuration, or do not want to modify it.

You could also modify the default transport used by the "net/http" package. This would affect your entire program (including the default HTTP client).

proxyUrl, err := url.Parse("http://proxyIp:proxyPort")
http.DefaultTransport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)}

这篇关于为HTTP客户端设置代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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