How to Retrieve the Final URL After Redirects in Go's http.NewRequest
When making HTTP requests with http.NewRequest, you may encounter situations where the server redirects the request. To extract query strings from the final URL, you need to find the URL the request ultimately ended up at.
Despite the lack of an explicit field in the http.Response object, there is a way to obtain the final URL:
Using an Anonymous Function to Check Redirects
An anonymous function can be used to capture and save the final redirect URL. Here's an example:
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)
The CheckRedirect function provided to the client wraps the default check redirect mechanism. It checks the number of redirects and saves the final URL query in the lastUrlQuery variable. Once the request execution completes, you can access the final URL via lastUrlQuery.
The above is the detailed content of How to Get the Final URL After Redirects Using Go\'s http.NewRequest?. For more information, please follow other related articles on the PHP Chinese website!