http - 为什么 Go 中的 http 客户端在发出 https 请求时会通过代理返回 Unauthorized?

标签 http go https proxy

我一直在尝试通过代理从我一直在使用 Go 的客户端发出 GET 请求。

curl 等价物可能看起来有点像这样:

curl -v -x example.proxy.com:8080 -U username:password 'https://example.com'

虽然像这样的东西会起作用,但 Go 中的等价物似乎不起作用,这是一个例子:

auth := "username:password"

basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))

proxyURL, _ := url.Parse("http://example.proxy.com:8080")
url, _ := url.Parse("https://example.com")

transport := &http.Transport{
    Proxy: http.ProxyURL(proxyURL),
}
client := &http.Client{
    Transport: transport,
}

request, _ := http.NewRequest("GET", url.String(), nil)
request.Header.Add("Proxy-Authorization", basic)
request.Header.Add("Proxy-Connection", "Keep-Alive")

response, _ := client.Do(request)

两者之间的唯一区别是 curl 命令在向 http 和 https url 发出请求时会成功,Go 代码将在 http 上工作,但在上面的示例中 (https://example. com,或任何其他 https URL),这将返回未授权状态。

我觉得我在这里遗漏了一些非常明显的东西,但似乎无法深入了解它。

最佳答案

您在 http.Request 上设置了一个 header ,该 header 被发送到上游服务器,而不是代理。您可以在代理 *url.URL 中设置基本身份验证:

proxyURL, _ := url.Parse("http://127.0.0.1:8080")
proxyURL.User = url.UserPassword("username", "password")

client := &http.Client{
    Transport: &http.Transport{
        Proxy: http.ProxyURL(proxyURL),
    },
}

关于http - 为什么 Go 中的 http 客户端在发出 https 请求时会通过代理返回 Unauthorized?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39487798/

相关文章:

javascript - 除非使用alert(),否则AJAX请求不起作用

http - Axis 1.4 - 更改为使用 HTTP/1.1

html - golang 中的 JavaScript onClick 事件

post - 在带有 SuiteScript 2.0 的 NetSuite 中,无法使用内容类型为 multipart/form-data 的 HTTP POST 请求发送文件

css - 如何让 HTTPS 域拉入 CSS 数据?

android - android 应用程序 : javax.net.ssl.SSLPeerUnverifiedException 中的错误:没有对等证书

http - 哪些浏览器的后退按钮不会向服务器生成请求?

http - 文件服务器不会提供超过 32 KB 的文件

go - 使用 Go 获取 Google 的数据存储键值

go - 在 nil 结构指针上调用方法不会 panic。为什么不?