Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the http redirect status codes

Tags:

redirect

http

go

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?

like image 928
10 cls Avatar asked Jul 04 '14 15:07

10 cls


1 Answers

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

like image 186
James Henstridge Avatar answered Sep 17 '22 21:09

James Henstridge