且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-05-04 05:17:50

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