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 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器