How to get the http redirect status codes in Golan

2020-08-15 07:58发布

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 redirect go
1条回答
狗以群分
2楼-- · 2020-08-15 08:19

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{}}

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

查看更多
登录 后发表回答