How to Determine the Final URL After Redirects in Golang?

DDD
Release: 2024-11-11 16:59:03
Original
504 people have browsed it

How to Determine the Final URL After Redirects in Golang?

Determining Final URL after Redirects in Golang

In the net/http package of Golang, HTTP GET requests can encounter redirects, which can lead to a final destination URL that differs from the initial request. This predicament raises the question: how can we determine the final URL reached after a series of redirects without resorting to cumbersome workarounds?

The Solution

Contrary to the assumption that a hackish approach is necessary, a clean and straightforward solution exists within the Response object returned by the HTTP GET operation. This object holds the Request object that initiated the request, which provides access to the final URL visited.

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

    // Function to retrieve the final URL
    finalURL := resp.Request.URL.String()

    fmt.Printf("The URL you ended up at is: %v", finalURL)
}
Copy after login

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
Copy after login

This method allows for effortless retrieval of the final URL after any number of redirects. No additional customizations or global variable manipulations are necessary, ensuring a clean and efficient implementation.

The above is the detailed content of How to Determine the Final URL After Redirects in Golang?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template