How can I get the last followed URL use http.Client on 302 Redirections?

49 views
Skip to first unread message

Darren Hoo

unread,
May 21, 2018, 12:25:37 AM5/21/18
to golang-nuts
if this is how  the redirections go:

A (original url) => B => C => D

I want to know the url of request D

the URL of A is never changed, and get the Location header from request is impossible.

Darren Hoo

unread,
May 21, 2018, 1:14:20 AM5/21/18
to golang-nuts
Found a hacky solution,  https://play.golang.org/p/jLlKR3yjWSw
Any better ideas?


var client = &http.Client{
CheckRedirect: setFollowURL,
}

func setFollowURL(req *http.Request, via []*http.Request) error {
via[0].URL = req.URL
if len(via) >= 10 {
return errors.New("stopped after 10 redirects")
}
return nil
}

Dave Cheney

unread,
May 21, 2018, 4:25:05 AM5/21/18
to golang-nuts
Please keep in mind that the Via header is supplied by he client (the browser) and there is not requirement that it maintains the full chain of custardy of all the urls it has passed though, nor is there any way for Go to know nor enforce that this list remains accurate. Sorry.

Darren Hoo

unread,
May 21, 2018, 5:50:02 AM5/21/18
to golang-nuts
Hi Dave,

I haven't made it clear on the first post, sorry,

I am talking about the behavior of  Go's net/http.Client, so there are no browsers involved.
Go's net/http.Client will do redirections transparently for user, but there are no exposed way of get the redirected url.

see https://play.golang.org/p/jLlKR3yjWSw ,  that explains what I want to achieve. 
Reply all
Reply to author
Forward
0 new messages