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

How to Determine the Final URL After Redirects in Go?

Linda Hamilton
Release: 2024-11-10 22:38:02
Original
777 people have browsed it

How to Determine the Final URL After Redirects in Go?

Determining the Final URL After Redirects in Go

In Go's net/http package, when making GET or POST requests, you may encounter situations where the server responds with a redirect. To handle this automatically, the client performs the redirect transparently in the background. However, this can make it challenging to determine the final URL reached after a series of redirects.

Fortunately, Go provides a simple and effective solution to retrieve the final URL. Within the HTTP response, the Request object contains the final URL attempted by the client.

Here's an example demonstrating how to obtain the final URL:

package main

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

func main() {
    // Perform the request. It could go through multiple redirections.
    resp, err := http.Get("http://example.com/path/to/resource")
    if err != nil {
        log.Fatalf("http.Get => %v", err.Error())
    }

    // Extract the final URL from the request in the response.
    finalURL := resp.Request.URL.String()

    fmt.Println("The final URL reached is:", finalURL)
}
Copy after login

In this code, the Request object within the HTTP response holds the final URL after all redirects have occurred. The program prints this final URL to the console.

This approach is cleaner than using hackish workarounds and gives you direct access to the last URL accessed by the client. It ensures that you can easily track and record the entire redirect chain, if necessary.

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