net/http忽略系统代理设置。

huangapple go评论82阅读模式
英文:

net/http ignoring system proxy settings

问题

你好!以下是翻译好的内容:

我正在使用Charles来调试HTTP请求,但是似乎Go的网络堆栈忽略了系统代理设置(在OSX上),请求没有被记录。

我该如何告诉Go使用代理来发送请求呢?

英文:

I'm using Charles to debug HTTP requests, but it seems that Go's network stack ignores the system proxy settings (on OSX) and the requests are not logged.

How do I tell Go that the requests should use the proxy?

答案1

得分: 7

我刚刚遇到了完全相同的问题,而且接受的解决方案对我没有起作用。这是因为我的$HTTP_PROXY环境变量没有设置!

我通过按照这里指示的设置我的环境变量来解决它:http://www.bonusbits.com/wiki/HowTo:Setup_Charles_Proxy_on_Mac 然后一旦变量设置正确,我甚至不需要为我的客户端应用自定义的Transport。它可以使用默认的传输方式工作。

也许是因为我使用了自定义的shell(zsh),这个过程没有自动发生。然而有趣的是,Python在同一个shell中可以在Charles Proxy中正确显示,而Go却不行。更新我的.zshrc(或者你使用的任何shell或配置文件)来导出适当的变量就可以解决问题。

英文:

I just had this exact issue, and the accepted solution did NOT solve it for me. That's because my $HTTP_PROXY environment variable was not set!

I was able to solve it by setting up my environment variables as per indicated here: http://www.bonusbits.com/wiki/HowTo:Setup_Charles_Proxy_on_Mac Then once the variable was set correctly, I didn't even need to apply a custom Transport to my client. It worked with the default transport.

Perhaps because I'm using a custom shell (zsh) this didn't happen automatically. However what's interesting is that python would correct appear in Charles Proxy in the same shell while Go would not. Updating my .zshrc (or whatever shell or profile you are using's config) to export the appropriate variables worked.

答案2

得分: 3

你可以使用ProxyFromEnvironment函数获取代理信息。然后,你可以使用具有代理设置信息的传输(由RoundTripper接口表示)创建HTTP客户端:

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

client := http.Client{Transport: PTransport}

然后,你只需使用传输从传递的函数获取的信息进行HTTP请求,将其传递给Proxy结构字段。代理信息将从$HTTP_PROXY环境变量中获取。

英文:

You can get proxy info using ProxyFromEnvironment function. Then you create http client using transport (represented by RoundTripper interface) that has info about your proxy settings:

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

client := http.Client{Transport: PTransport}

Then you just do http request using the info transport gets from passed function to Proxy struct field. Proxy info will be taken from $HTTP_PROXY environment variable.

huangapple
  • 本文由 发表于 2013年8月12日 20:34:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/18187136.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定