Home > Article > Backend Development > How to Get the Final URL After Redirects in Go\'s `http.Client`?
Extracting the Final URL After Redirect in Http.Go
While using http.NewRequest to make HTTP requests, you may encounter the need to extract query strings from the final URL after any redirects. The Response object does not inherently provide access to the final URL.
To retrieve the URL after redirects:
Here's a code snippet demonstrating this approach:
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)
By using this technique, you can capture the final URL after all redirects have occurred, allowing you to access query strings and other information from the final destination.
The above is the detailed content of How to Get the Final URL After Redirects in Go\'s `http.Client`?. For more information, please follow other related articles on the PHP Chinese website!