debugging 如何在Golang内置HTTP客户端中获取HTTP代理响应头?

slsn1g29  于 2022-11-24  发布在  Go
关注(0)|答案(1)|浏览(141)

我正在通过HTTP代理使用默认的“net/http”Golang lib执行一个简单的HTTPGET请求,并希望读取第一个代理应答的内容(对于使用CONNECT方法的HTTP客户机请求)。

HTTP/1.1 200 OK
Request-Uid: <some id>
<another header>: <another value>

Golang代码:

...
proxyUrlParsed, errUrl := url.Parse(proxyUrl)
tr := &http.Transport{
   Proxy:   http.ProxyURL(proxyUrlParsed),
}
client := &http.Client{
   Transport: tr,
}
request, errReq := http.NewRequest("GET", targetUrl, nil)
response, errDo := client.Do(request)
// Response contains HTTP headers from the reply from the target resource but not the intermediate proxy.

我用DialContext部分地解决了这个问题,但是我需要实现协议的一些部分,我发现这些部分对于以后的支持来说不是那么方便和昂贵。

gxwragnw

gxwragnw1#

隧道代理

以curl客户端的使用为例,在请求https时,使用CONNECT方法连接隧道连接,得到的流内容是TLS加密的内容,代理无法解密。
如果有tls证书,可以尝试解析响应流。
wireshark捕获https请求时,需要在浏览器中配置一个参数,证书保存在指定的文件中
第一个

反向代理服务器

使用/net/http/httputil.ReverseProxy代理请求,将ModifyResponse字段设置为响应挂钩。

package main

import (
    "log"
    "net/http"
    "net/http/httputil"
    "net/url"
)

func main() {
    proxy := httputil.NewSingleHostReverseProxy(&url.URL{Scheme: "http", Host: "127.0.0.1:8020"})
    proxy.ModifyResponse = func(w *http.Response) error {
        w.Header.Add("Author", "eudore")
        log.Println(w.Request.Method, w.Request.RequestURI, w.Status)
        return nil
    }
    http.ListenAndServe(":8021", proxy)
}

curl请求:

[root@node1 ~]# curl -I  127.0.0.1:8020?222
HTTP/1.1 401 Unauthorized
Www-Authenticate: Basic
Date: Thu, 17 Nov 2022 01:34:06 GMT

[root@node1 ~]# curl -I  127.0.0.1:8021?222
HTTP/1.1 401 Unauthorized
Author: eudore
Date: Thu, 17 Nov 2022 01:34:07 GMT
Www-Authenticate: Basic

相关问题