Home >Backend Development >Golang >How to Determine the Final URL After Redirections in Go?

How to Determine the Final URL After Redirections in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-15 05:02:02314browse

How to Determine the Final URL After Redirections in Go?

Retrieving Final URL after Redirections in Go

In Go's net/http package, with automatic redirection handling, numerous URLs often result in a specific terminal URL. Determining the final URL after a sequence of redirections can be a challenge.

One possible solution without employing a hackish workaround lies in examining the Request component of the Response object. The Request object corresponds to the ultimate URL accessed by the client.

package main

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())
    }

    finalURL := resp.Request.URL.String()

    fmt.Printf("The URL you ended up at is: %v\n", finalURL)
}

This code retrieves the final URL after possible redirections and prints it using the Request.URL.String() method.

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 approach eliminates the need for complicated computations and provides a straightforward way to determine the final destination of redirecting URLs in Go.

The above is the detailed content of How to Determine the Final URL After Redirections 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