How to Get the Final URL After Redirects in Go\'s `http.Client`?

Susan Sarandon
Release: 2024-11-16 18:07:02
Original
256 people have browsed it

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:

  1. Create an anonymous function within the CheckRedirect callback.
  2. Within the anonymous function, set the lastUrlQuery variable to the RequestURI() of the redirected request.
  3. Return nil to allow the redirect.

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template