在Go中,我可以在请求重定向时检查响应吗? [英] In Go, can I check response when the request is redirected?

查看:218
本文介绍了在Go中,我可以在请求重定向时检查响应吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以注册 CheckRedirect ,以在请求重定向时检查下一个请求。有没有一种方法可以在第一次请求被重定向时得到响应?

目前实现的方式是,似乎没有可能在默认情况下查看响应(除非您自己实现 Do())。

请参阅 src / net / http /client.go#L384-L399

  if shouldRedirect(resp.StatusCode ){
//读取正文,如果很小,基础TCP连接将被重新使用。
//无需检查错误:如果失败,传输将无法重复使用。
const maxBodySlurpSize = 2<< 10
如果resp.ContentLength == -1 || resp.ContentLength< = maxBodySlurpSize {
io.CopyN(ioutil.Discard,resp.Body,maxBodySlurpSize)
}
resp.Body.Close()
如果urlStr = resp .Header.Get( 位置); urlStr =={
err = fmt.Errorf(%d响应丢失位置标题,resp.StatusCode)
break
}
ase = req.URL
via = append(via,req)
continue
}


We can register CheckRedirect to check the next request when the request is redirected. Is there a way that I can get the response for the first request when it's redirected?

解决方案

The way it is currently implemented, it doesn't seem possible to have a look at the response by default (unless you implement yourself 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
    }

这篇关于在Go中,我可以在请求重定向时检查响应吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆