Tracking Go HTTP Redirection History


This post will explain how to track HTTP redirection history in Golang.

(WIP)

Solution

func Redirections(resp *http.Response) (history []*http.Request) {
	for resp != nil {
		req := resp.Request
		history = append(history, req)
		resp = req.Response
	}
	return
}

This returns all requests made for a particular response in a slice.

Note that the last request(that eventually made the response) comes first in the slice, so to reverse the order, use this technique(taken from https://github.com/golang/go/wiki/SliceTricks#reversing):

for l, r := 0, len(history)-1; l < r; l, r = l+1, r-1 {
    history[l], history[r] = history[r], history[l]
}

Now you can use this function as:

resp, err := http.Get("http://naver.com")
if err != nil {
    panic(err)
}
defer resp.Body.Close()
for _, req := range Redirections(resp) {
    fmt.Println(req.URL)
}
// Output:
// https://www.naver.com/
// http://www.naver.com/
// http://naver.com

(Due to a temporal issue with httpbin, I chose the famous Korean search engine Naver which redirects users to https:// page using HTTP redirects)