Home > Backend Development > Golang > How Do I Extract the Final URL After Redirects in Go?

How Do I Extract the Final URL After Redirects in Go?

Mary-Kate Olsen
Release: 2024-11-12 12:57:02
Original
471 people have browsed it

How Do I Extract the Final URL After Redirects in Go?

Extracting the Final URL in Go after Redirects

In Go's "net/http" package, retrieving a URL that undergoes multiple redirects can invoke automatic redirection handling. However, determining the final destination URL can prove challenging without implementing a hackish workaround.

Solution: Leveraging Response Object

Fortunately, a more elegant solution exists. The "Response" object returned by "http.Get" (or other HTTP method functions) contains an "Request" field that represents the last attempted access. This can be utilized to extract the final URL.

package main

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

func main() {
    // Initiate a GET request for a URL subject to redirects
    resp, err := http.Get("https://google.com") // Replace with the target URL
    if err != nil {
        log.Fatalf("http.Get -> %v", err)
    }

    // Retrieve the final URL using the last attempted Request in the Response
    finalURL := resp.Request.URL.String()

    // Output the resolved final URL
    fmt.Printf("The URL you ended up at is: %s", finalURL)
}
Copy after login

The above is the detailed content of How Do I Extract the Final URL After Redirects in Go?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template