http - 如何获取 http 重定向状态码

标签 http redirect go

我想记录 301 和 302,但在 Client.Do、Get、doFollowingRedirects、CheckRedirect 中看不到读取响应状态代码的方法。我是否必须自己实现重定向才能实现这一点?

最佳答案

http.Client type 允许你指定一个自定义传输,它应该允许你做你想要的。应该执行以下操作:

type LogRedirects struct {
    Transport http.RoundTripper
}

func (l LogRedirects) RoundTrip(req *http.Request) (resp *http.Response, err error) {
    t := l.Transport
    if t == nil {
        t = http.DefaultTransport
    }
    resp, err = t.RoundTrip(req)
    if err != nil {
        return
    }
    switch resp.StatusCode {
    case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect:
        log.Println("Request for", req.URL, "redirected with status", resp.StatusCode)
    }
    return
}

(如果您只支持链接到默认传输,则可以稍微简化一下)。

然后您可以使用此传输创建客户端,并且应记录所有重定向:

client := &http.Client{Transport: LogRedirects{}}

这是一个完整的示例,您可以尝试:http://play.golang.org/p/8uf8Cn31HC

关于http - 如何获取 http 重定向状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24577494/

相关文章:

http - Vibed:错误:411 需要长度

http - 多个http请求

C# HttpClient 的每个实例都获得它自己的 ServicePoint

ios - AWS 放大添加身份验证 : how to add a redirect signin URI after executing the amplify cli

json - 从 Map 和 Struct 编码的 JSON 中的排序差异

c# - C# 中的 HTTP 服务器支持分块传输编码

java - Jersey - 使用 Get Not Put 重定向,导致重定向循环

zend-framework - 在前端 Controller 插件 Zend 中重定向

json - 在 Go 中查询 Magento API

go - osxfuse cgofuse mkdir 输入/输出错误