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

Linda Hamilton
Release: 2024-11-26 02:05:11
Original
922 people have browsed it

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

How to Get URLs After Client Directs

In Go's http package, making multiple http requests for querying strings is common. However, extracting these strings from the final URL can be challenging, especially when redirects occur. Unfortunately, the Response object lacks information regarding this final URL.

Despite the availability of redirect prevention options, this article focuses on obtaining the URL after a request has been made. To achieve this:

  1. Create a new http request using http.NewRequest.
  2. Set up an http.Client to handle the request.
  3. Use an anonymous function to set up the client. The anonymous function allows for the URL query to be stored in a variable.
  4. Execute the request using client.Do.
  5. Retrieve the stored URL query.

Here's an example code snippet:

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

func main() {
    req, err := http.NewRequest("GET", "URL", nil)
    if err != nil {
        log.Fatal(err)
    }
    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 {
        log.Fatal(err)
    }
    fmt.Printf("last url query is %v\n", lastUrlQuery)
}
Copy after login

This code will redirect the request and will save the final URL query in lastUrlQuery.

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