Determining Final URL after Redirects in Golang
In the net/http package of Golang, HTTP GET requests can encounter redirects, which can lead to a final destination URL that differs from the initial request. This predicament raises the question: how can we determine the final URL reached after a series of redirects without resorting to cumbersome workarounds?
The Solution
Contrary to the assumption that a hackish approach is necessary, a clean and straightforward solution exists within the Response object returned by the HTTP GET operation. This object holds the Request object that initiated the request, which provides access to the final URL visited.
import ( "fmt" "log" "net/http" ) func main() { resp, err := http.Get("http://stackoverflow.com/q/16784419/727643") if err != nil { log.Fatalf("http.Get => %v", err.Error()) } // Function to retrieve the final URL finalURL := resp.Request.URL.String() fmt.Printf("The URL you ended up at is: %v", finalURL) }
Output:
The URL you ended up at is: http://stackoverflow.com/questions/16784419/in-golang-how-to-determine-the-final-url-after-a-series-of-redirects
This method allows for effortless retrieval of the final URL after any number of redirects. No additional customizations or global variable manipulations are necessary, ensuring a clean and efficient implementation.
The above is the detailed content of How to Determine the Final URL After Redirects in Golang?. For more information, please follow other related articles on the PHP Chinese website!