使用身份验证去http代理 [英] Go http proxy with auth

查看:261
本文介绍了使用身份验证去http代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用PostForm方法将代理与auth一起使用. 如果我使用类似(简体)的内容:

I need to use a proxy with auth using PostForm method. If I use something like (simplified):

request, err := http.NewRequest("GET", url.String(), nil)
response, err := client.Do(request)

我可以轻松地执行request.Header.Add("Proxy-Authorization", basicAuth),而且效果很好. 但是现在,我正在编辑第三方程序包,并尝试将代理添加到现有代码中:

I can with ease do request.Header.Add("Proxy-Authorization", basicAuth) and it works fine. But now, I am editing third-party package, and I try to add proxy to the existing code:

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

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

    resp, err := bot.Client.PostForm(method, params)

    auth := "username:password"
    basicAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth)) 
    resp.Header.Add("Proxy-Authorization", basicAuth)

在我看来,它在字符串resp.Header.Add("Proxy-Authorization", basicAuth)上不起作用,并且失败了. 在此示例中,没有身份验证的代理可以正常工作. 有人知道吗,在这种情况下我可以在auth中使用代理吗?

It does not work, and it fails, to my mind, at string resp.Header.Add("Proxy-Authorization", basicAuth). Proxy without auth works fine, in this example. Does anybody know, can I use proxy with auth in this case?

推荐答案

您正在尝试向响应中添加标头,这不是您发送到服务器的内容,而是您收到的内容.您必须向请求中添加标头和数据,您必须先将其组装,然后再像这样执行它:

You are trying to add a header to a response, which isn't what you send to the server but what you receive. You have to add headers and data to the request, which you have to assemble first and then execute it like this:

data := url.Values{} // the form data
data.Add("foo-key", "some data")
req, err := http.NewRequest("POST","https://yoururl", strings.NewReader(data.Encode()))
auth := "username:password"
basicAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
req.Header.Add("Proxy-Authorization", basicAuth)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err := bot.Client.Do(req)

然后您只使用响应(resp)

这篇关于使用身份验证去http代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆