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)
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")
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!