Determining the Final URL After Redirects in Go
In Go's net/http package, when making GET or POST requests, you may encounter situations where the server responds with a redirect. To handle this automatically, the client performs the redirect transparently in the background. However, this can make it challenging to determine the final URL reached after a series of redirects.
Fortunately, Go provides a simple and effective solution to retrieve the final URL. Within the HTTP response, the Request object contains the final URL attempted by the client.
Here's an example demonstrating how to obtain the final URL:
package main import ( "fmt" "log" "net/http" ) func main() { // Perform the request. It could go through multiple redirections. resp, err := http.Get("http://example.com/path/to/resource") if err != nil { log.Fatalf("http.Get => %v", err.Error()) } // Extract the final URL from the request in the response. finalURL := resp.Request.URL.String() fmt.Println("The final URL reached is:", finalURL) }
In this code, the Request object within the HTTP response holds the final URL after all redirects have occurred. The program prints this final URL to the console.
This approach is cleaner than using hackish workarounds and gives you direct access to the last URL accessed by the client. It ensures that you can easily track and record the entire redirect chain, if necessary.
The above is the detailed content of How to Determine the Final URL After Redirects in Go?. For more information, please follow other related articles on the PHP Chinese website!