Home > Backend Development > Golang > How to Query URLs Without Redirects in Go?

How to Query URLs Without Redirects in Go?

Barbara Streisand
Release: 2024-12-07 14:10:14
Original
686 people have browsed it

How to Query URLs Without Redirects in Go?

Querying URLs Without Redirects in Go

When testing redirect scripts, it can be necessary to query a URL without triggering the redirect. This is particularly useful for logging redirect URLs or errors. There are two approaches to achieve this in Go.

Using the Default Transport

The first method involves using the http.DefaultTransport object, which allows for greater control over the request handling process. By utilizing the RoundTrip function, it is possible to execute the HTTP request without following any redirects.

req, err := http.NewRequest("GET", "http://example.com/redirectToAppStore", nil)
// ...
resp, err := http.DefaultTransport.RoundTrip(req)
Copy after login

Using the CheckRedirect Field

Alternatively, the second method leverages the CheckRedirect field of an http.Client. By setting this field to func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, it effectively disables redirect processing for subsequent requests executed through the client.

client := &http.Client{
    CheckRedirect: func(req *http.Request, via []*http.Request) error {
        return http.ErrUseLastResponse
    },
}
resp, err := client.Get("http://example.com/redirectToAppStore")
Copy after login

Performance Considerations

In the context of benchmarking, it is important to note that the first solution (http.DefaultTransport.RoundTrip) exhibits performance issues when making numerous requests in parallel. This is due to the potential for connection reuse within the transport.

For scenarios where individual requests require separate connections, it is recommended to use the second solution (CheckRedirect field) and create a new client for each request. This ensures that connections are closed after each query and not reused.

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