如何获取http重定向状态代码 [英] How to get the http redirect status codes

查看:64
本文介绍了如何获取http重定向状态代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想记录301s和302s,但看不到Client.Do,Get,doFollowingRedirects,CheckRedirect中读取响应状态代码的方法.我是否需要自己实施重定向才能实现这一目标?

I'd like to log 301s vs 302s but can't see a way to read the response status code in Client.Do, Get, doFollowingRedirects, CheckRedirect. Will I have to implement redirection myself to achieve this?

推荐答案

http.Client 类型允许您指定自定义传输方式,这应该允许您执行后续操作.应该执行以下操作:

The http.Client type allows you to specify a custom transport, which should allow you to do what you're after. Something like the following should do:

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
}

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

(you could simplify this a little if you only support chaining to the default transport).

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

You can then create a client using this transport, and any redirects should be logged:

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

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

Here is a full example you can experiment with: http://play.golang.org/p/8uf8Cn31HC

这篇关于如何获取http重定向状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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