Extracting the Final URL in Go after Redirects
In Go's "net/http" package, retrieving a URL that undergoes multiple redirects can invoke automatic redirection handling. However, determining the final destination URL can prove challenging without implementing a hackish workaround.
Solution: Leveraging Response Object
Fortunately, a more elegant solution exists. The "Response" object returned by "http.Get" (or other HTTP method functions) contains an "Request" field that represents the last attempted access. This can be utilized to extract the final URL.
package main import ( "fmt" "log" "net/http" ) func main() { // Initiate a GET request for a URL subject to redirects resp, err := http.Get("https://google.com") // Replace with the target URL if err != nil { log.Fatalf("http.Get -> %v", err) } // Retrieve the final URL using the last attempted Request in the Response finalURL := resp.Request.URL.String() // Output the resolved final URL fmt.Printf("The URL you ended up at is: %s", finalURL) }
The above is the detailed content of How Do I Extract the Final URL After Redirects in Go?. For more information, please follow other related articles on the PHP Chinese website!