我们可以注册CheckRedirect以在重定向请求时检查下一个请求。有没有办法可以在第一个请求重定向时获得响应?
答案 0 :(得分:2)
你想对第一个回复做什么?这将非常无聊。
我认为最明智的做法是自动禁用重定向(始终从CheckRedirect
返回非零错误)并自行处理重定向,在这种情况下,您可以完全访问所有请求/响应。< / p>
答案 1 :(得分:2)
目前实施的方式,默认情况下似乎无法查看响应(除非您自己实现Do()
所做的事情。)
见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 :(得分:0)
我的解决方法:
可以在自定义 RoundTripper
中修补任何 http 请求/响应,包括重定向:
type RedirectChecker struct{}
func (RedirectChecker) RoundTrip(req *http.Request) (*http.Response, error) {
// e.g. patch the request before send it
req.Header.Set("user-agent", "curl/7.64.1")
resp, err := http.DefaultTransport.RoundTrip(req)
if err == nil && resp != nil {
switch resp.StatusCode {
case
http.StatusMovedPermanently,
http.StatusFound,
http.StatusTemporaryRedirect,
http.StatusPermanentRedirect:
// e.g. stop further redirections
// roughly equivalent to http.ErrUseLastResponse
resp.StatusCode = http.StatusOK
// e.g. read the Set-Cookie headers
// unfortunately cookie jars do not handle redirects in a proper manner
// and that's why I came to this question...
fmt.Printf("%+v", resp.Cookies())
}
}
}
httpClient := &http.Client{Transport: RedirectChecker{}}
httpClient.Do(...)