In Go's http package, making multiple http requests for querying strings is common. However, extracting these strings from the final URL can be challenging, especially when redirects occur. Unfortunately, the Response object lacks information regarding this final URL.
Despite the availability of redirect prevention options, this article focuses on obtaining the URL after a request has been made. To achieve this:
Here's an example code snippet:
import ( "fmt" "log" "net/http" ) func main() { req, err := http.NewRequest("GET", "URL", nil) if err != nil { log.Fatal(err) } 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\n", lastUrlQuery) }
This code will redirect the request and will save the final URL query in lastUrlQuery.
The above is the detailed content of How to Retrieve the Final URL After HTTP Redirects in Go?. For more information, please follow other related articles on the PHP Chinese website!