Home >Backend Development >Golang >How to Get the Final URL After Redirects Using Go\'s http.NewRequest?

How to Get the Final URL After Redirects Using Go\'s http.NewRequest?

DDD
DDDOriginal
2024-11-23 13:14:14613browse

How to Get the Final URL After Redirects Using Go's http.NewRequest?

How to Retrieve the Final URL After Redirects in Go's http.NewRequest

When making HTTP requests with http.NewRequest, you may encounter situations where the server redirects the request. To extract query strings from the final URL, you need to find the URL the request ultimately ended up at.

Despite the lack of an explicit field in the http.Response object, there is a way to obtain the final URL:

Using an Anonymous Function to Check Redirects

An anonymous function can be used to capture and save the final redirect URL. Here's an example:

req, err := http.NewRequest("GET", URL, nil)
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", lastUrlQuery)

The CheckRedirect function provided to the client wraps the default check redirect mechanism. It checks the number of redirects and saves the final URL query in the lastUrlQuery variable. Once the request execution completes, you can access the final URL via lastUrlQuery.

The above is the detailed content of How to Get the Final URL After Redirects Using Go\'s http.NewRequest?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn