为 HTTP 客户端设置代理 [英] Setting up proxy for HTTP client
问题描述
我正在尝试设置 HTTP 客户端,以便它使用代理,但是我不太明白该怎么做.该文档多次引用代理",但似乎没有一个函数允许定义代理.我需要的是这样的:
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
知道如何在 Go 中做到这一点吗?
Any idea how to do this in Go?
推荐答案
lukad 是正确的,你可以设置 HTTP_PROXY
环境变量,如果你这样做 Go 将默认使用它.
lukad is correct, you could set the HTTP_PROXY
environment variable, if you do this Go will use it by default.
重击:
export HTTP_PROXY="http://proxyIp:proxyPort"
去:
os.Setenv("HTTP_PROXY", "http://proxyIp:proxyPort")
您也可以构建自己的 http.Client,无论环境配置如何,它都必须使用代理:
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.
您还可以修改net/http
"包使用的默认传输.这会影响您的整个程序(包括默认的 HTTP 客户端).
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屋!