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

How to Query URLs in Go without Following Redirects?

Susan Sarandon
Release: 2024-11-24 20:13:46
Original
838 people have browsed it

How to Query URLs in Go without Following Redirects?

Querying URLs without Redirection in Go

In benchmark testing for a redirect script, it is necessary to query a URL without initiating an automatic redirect. This requires preventing the program from downloading the redirected content while still logging the redirect URL or any associated errors.

Solution 1: Using http.DefaultTransport.RoundTrip

One approach is to leverage the http.DefaultTransport.RoundTrip() function within your http.Request. Unlike http.Client, Transport does not automatically follow redirects:

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

However, this solution may encounter performance issues and errors under high-load scenarios.

Solution 2: Setting CheckRedirect to False

Alternatively, you can modify the CheckRedirect field of the http.Client to disable automatic redirects:

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

This method ensures consistent performance, but it does not guarantee the closure of connections after each query.

Ensuring Connection Closure

To enforce connection closure, you can create a new HTTP client for each request:

for i := 0; i < n; i++ {
    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

This approach ensures that each query uses a fresh connection, preventing performance issues due to connection reuse.

The above is the detailed content of How to Query URLs in Go without Following Redirects?. 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