Search code examples
gohttpserverhttp-proxy

Go RoundTrip/Transport Proxy Address


I understand that the Proxy field of http.Transport asks for a function that generates proxy server addresses. So this is my roundtripper:

roundtripper := &http.Transport{
    Proxy: proxyrouter.Calculateproxy,
...
}

So the type of Proxy is func(*Request) (*url.URL, error). This gets linked to the server and is later on called with:

response := roundtripper.RoundTrip(request)

Which returns the response. Now is there any way to know what proxy address was used to get this response? (since my Calculateproxy function just takes random addresses)


Solution

  • Have the Proxy function add a header to record the proxy server used:

    Transport{
        Proxy: func(req *Request) (*url.URL, error) {
            p, err := proxyrouter.Calculateproxy(req)
            if err != nil {
                return err
            }
            req.Header.Set("X-Proxy-Addr", p.String())
            return req, nil
        },
    }
    

    The http.Response has a reference to the originating request

    proxy := resp.Request.Header.Get("X-Proxy-Addr")