Retrieving the Final URL in Http.Go
How do you extract the final URL after a series of HTTP requests, including any redirects? The provided code uses http.NewRequest to initiate the requests, but the Response object doesn't contain a field for the final URL.
Solution:
One approach is to utilize an anonymous function and http.Client.CheckRedirect. By defining a custom CheckRedirect function, you can capture the last URL query before the redirect. Here's an example:
import ( "fmt" "io" "net/http" ) func main() { req, err := http.NewRequest("GET", "https://example.com", nil) if err != nil { // Handle error } 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 { // Handle error } io.Copy(io.Discard, resp.Body) fmt.Printf("Last URL query: %s\n", lastUrlQuery) }
In this code, lastUrlQuery captures the URL query before each redirect. When the redirect chain completes or reaches a limit (set to 10 in the example), the final URL query is stored in lastUrlQuery.
The above is the detailed content of How to Get the Final URL After HTTP Redirects in Go?. For more information, please follow other related articles on the PHP Chinese website!