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)
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")
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") // ... }
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!