In Go, can I check the response when a request is redirected?

We can register CheckRedirect to check the next request when redirecting the request. Is there a way to get a response to the first request when redirecting it?

+2
source share
2 answers

What do you want to do with the first answer? It will be pretty boring.

I think that it would be most reasonable to automatically disable subsequent redirects (always return a non-nil error from CheckRedirect ) and handle the redirection yourself, in which case you have full access to all requests / answers.

+2
source

The way it is currently implemented does not seem possible to look at the default answer (unless you implement yourself, which is what Do() does).
See src/net/http/client.go#L384-L399 :

 if shouldRedirect(resp.StatusCode) { // Read the body if small so underlying TCP connection will be re-used. // No need to check for errors: if it fails, Transport won't reuse it anyway. const maxBodySlurpSize = 2 << 10 if resp.ContentLength == -1 || resp.ContentLength <= maxBodySlurpSize { io.CopyN(ioutil.Discard, resp.Body, maxBodySlurpSize) } resp.Body.Close() if urlStr = resp.Header.Get("Location"); urlStr == "" { err = fmt.Errorf("%d response missing Location header", resp.StatusCode) break } base = req.URL via = append(via, req) continue } 
+2
source

Source: https://habr.com/ru/post/1241834/


All Articles