How to get current url in http.go?

I am using http.NewRequest to create multiple HTTP requests (obviously). Now I need to make a request and extract the query strings from the final URL (there is a redirect).

So the question is how to find the URL (if the final URL, if the client was redirected)? There is no such field in Response .

Note that I do not need to stop the redirect ... just to find out what the url is after the request

+3
source share
2 answers

You are adding a callback to http.Client.CheckRedirect

  // CheckRedirect specifies the policy for handling redirects. // If CheckRedirect is not nil, the client calls it before // following an HTTP redirect. The arguments req and via are // the upcoming request and the requests made already, oldest // first. If CheckRedirect returns an error, the Client Get // method returns both the previous Response and // CheckRedirect error (wrapped in a url.Error) instead of // issuing the Request req. // // If CheckRedirect is nil, the Client uses its default policy, // which is to stop after 10 consecutive requests. CheckRedirect func(req *Request, via []*Request) error 

You can then check the new request as soon as this happens. Just remember to set some kind of limit to prevent loop forwarding (as indicated in the docs, it is canceled after 10 by default).

+2
source

Although @JimB actually answered the question I am posting as it may help someone. I used an anonymous function. Perhaps this could have been done better using closure, but I still haven't figured out how locks work.

 req, err = http.NewRequest("GET", URL, nil) cl := http.Client{} var lastUrlQuery string cl.CheckRedirect = func(req *http.Request, via []*http.Request) error { if len(via) > 10 { return errors.New("too many redirects") } lastUrlQuery = req.URL.RequestURI() return nil } resp, err := cl.Do(req) if err != nil { log.Fatal(err) } fmt.Printf("last url query is %v", lastUrlQuery) 
+3
source

Source: https://habr.com/ru/post/1241831/


All Articles