How do I check HTTP redirect's target URL?

2,084 views
Skip to first unread message

Vasily Korytov

unread,
Sep 15, 2015, 2:57:47 PM9/15/15
to golang-nuts
Hi,

http.Get follows HTTP redirects. I don't want to follow the redirect, but want to check the redirect URL.

How do I do this? There is a http.client.checkRedirect function, that should be tweaked when customising this behaviour. But how do I check the redirect URL inside it?

I have something like:

var client = &http.Client{}
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
        return errors.New("redirects to " + req.URL.String())
}
var url = "http://localhost"
var newurl = "https://localhost"
req, err = http.Get(url, nil)

This fails on every redirect. I would like to check if req.URL matches the newurl. But how? I pass no this parameter to CheckRedirect, so this variable is not accessible in that scope.

Is that possible in some easy way?

Giulio Iotti

unread,
Sep 15, 2015, 3:36:10 PM9/15/15
to golang-nuts
On Tuesday, September 15, 2015 at 9:57:47 PM UTC+3, Vasily Korytov wrote:
Hi,

http.Get follows HTTP redirects. I don't want to follow the redirect, but want to check the redirect URL.
[...]

Is that possible in some easy way?

Yes, the documentation[1] is very clear.

The redirect check is like this: CheckRedirect(nextRequest *http.Request, previousRequests []*http.Request)

To check that the host (+port!) doesn't change, something like this:

    req.URL.Host == via[len(via)-1].URL.Host

Remember to also check that len(via) is smaller than 10 (for example) to still avoid following too many redirects.

Giulio Iotti

unread,
Sep 15, 2015, 4:07:14 PM9/15/15
to golang-nuts
No, sorry, I misunderstood your question.

Make a type and implement CheckRedirect for your new type that contains the URL you want to check against.

Behind the scenes, if you pass a function with a receiver (a.checkRedirect(b, c)) it's like you call the function with the receiver as an argument (checkRedirect(a, b, c)).


-- 
Giulio Iotti
Reply all
Reply to author
Forward
0 new messages