Home  >  Article  >  Backend Development  >  How to Get the Final URL After HTTP Redirects in Go?

How to Get the Final URL After HTTP Redirects in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-25 19:14:11568browse

How to Get the Final URL After HTTP Redirects in Go?

Retrieving the Final URL in Http.Go

How do you extract the final URL after a series of HTTP requests, including any redirects? The provided code uses http.NewRequest to initiate the requests, but the Response object doesn't contain a field for the final URL.

Solution:

One approach is to utilize an anonymous function and http.Client.CheckRedirect. By defining a custom CheckRedirect function, you can capture the last URL query before the redirect. Here's an example:

import (
    "fmt"
    "io"
    "net/http"
)

func main() {
    req, err := http.NewRequest("GET", "https://example.com", nil)
    if err != nil {
        // Handle error
    }

    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 {
        // Handle error
    }
    io.Copy(io.Discard, resp.Body)
    fmt.Printf("Last URL query: %s\n", lastUrlQuery)
}

In this code, lastUrlQuery captures the URL query before each redirect. When the redirect chain completes or reaches a limit (set to 10 in the example), the final URL query is stored in lastUrlQuery.

The above is the detailed content of How to Get the Final URL After HTTP Redirects in Go?. 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