如何知道http客户端在给定请求中使用的代理

我正在通过一些代理服务器执行一些请求。定义要使用的代理 URL 的函数将从代理列表中随机选择。我想知道对于给定的请求,正在使用哪个代理URL。据我所知,使用代理服务器时,http标头保持不变,但tcp标头是更改的标头。


下面是一些代码来说明它(为简单起见,没有错误处理):


func main() {

    transport := &http.Transport{Proxy: chooseProxy}

    client := http.Client{Transport: transport}


    request, err := http.NewRequest(http.MethodGet, "https://www.google.com", nil)

    checkErr(err)


    // How to know here which proxy was used? Suppose the same client will perform several requests to different URL's.

    response, err := client.Do(request)

    checkErr(err)


    dump, _ := httputil.DumpRequest(response.Request, false)

    fmt.Println(dump)

}


func chooseProxy(request *http.Request) (*url.URL, error) {

    proxies := []string{"proxy1", "proxy2", "proxy3"}


    proxyToUse := proxies[rand.Intn(len(proxies))]


    return url.Parse(proxyToUse)

}

我假设即使使用相同的客户端,也会为每个请求调用传输中的 Proxy 函数,如“Proxy 指定一个函数以返回给定请求的代理”的文档。我说的对吗?


喵喵时光机
浏览 111回答 3
3回答

明月笑刀无情

您可以修改选择Proxy函数,以便保存选定的代理。为此,您可以将 chooseProxy func 转换为一种类型的方法,该方法将用作要保留的信息的存储:type proxySelector stringfunc (sel *proxySelector) chooseProxy(request *http.Request) (*url.URL, error) {&nbsp; &nbsp; proxies := []string{"proxy1", "proxy2", "proxy3"}&nbsp; &nbsp; proxyToUse := proxies[rand.Intn(len(proxies))]&nbsp; &nbsp; *sel = proxySelector(proxyToUse) // <-----&nbsp; &nbsp; return url.Parse(proxyToUse)}func main() {&nbsp; &nbsp; var proxy proxySelector&nbsp; &nbsp; transport := &http.Transport{Proxy: proxy.chooseProxy}&nbsp; // <-----&nbsp; &nbsp; client := http.Client{Transport: transport}&nbsp; &nbsp; request, err := http.NewRequest(http.MethodGet, "https://www.google.com", nil)&nbsp; &nbsp; checkErr(err)&nbsp; &nbsp; // How to know here which proxy was used? Suppose the same client will perform several requests to different URL's.&nbsp; &nbsp; response, err := client.Do(request)&nbsp; &nbsp; checkErr(err)&nbsp; &nbsp; dump, _ := httputil.DumpRequest(response.Request, false)&nbsp; &nbsp; fmt.Println(dump)&nbsp; &nbsp; fmt.Println("Proxy:", string(proxy))&nbsp; // <-----}

慕无忌1623718

一些HTTP代理添加了一个标头来告诉它们是谁。Viahttps://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Via

烙印99

包含目标 URI 的请求作为参数提供给 。因此,您可以在函数中已经拥有正确的映射,您只需要检查vs。 那里。requestchooseProxychooseProxyproxyToUserequest.URL如果您并不真正信任此映射实际完成的代码,则需要查看代码外部。例如,您可以使用Wireshark查看实际的网络流量,以查看访问哪个代理。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go