dongzou9047 2016-09-14 10:08
浏览 82
已采纳

发出https请求时,为什么Go中的http客户端会通过代理返回未经授权的信息?

I've been trying to make a GET request from a client I've been working on in Go, via a proxy.

The curl equivalent may look a bit like this:

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

While something like this will work, the equivalent in Go does not seem to, here's an example:

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)

The only difference between the two is that the curl command will be successful when making requests to both http and https urls, the Go code will work over http, but in the example above (https://example.com, or any other https URL), this will return a status of Unauthorized.

I feel like I'm missing something really obvious here, but can't seem to get to the bottom of it.

  • 写回答

1条回答 默认 最新

  • drxpt06820 2016-09-14 13:11
    关注

    You are setting a header on the http.Request that is being sent to the upstream server, not the proxy. You can set basic auth in the proxy *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),
        },
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大