Querying URLs Without Redirects in Go
In this article, we address the issue of querying a URL without triggering automatic redirects in Go. This is often necessary for benchmarking purposes or when you only need to log the redirect URL or errors.
Solution 1: Using http.DefaultTransport.RoundTrip
Create an http.Request object as usual. Instead of passing it to an http.Client, use http.DefaultTransport.RoundTrip() to make the request. This bypasses the http.Client's built-in redirect handling.
import "net/http" func QueryURLWithoutRedirect(url string) (*http.Response, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } return http.DefaultTransport.RoundTrip(req) }
Solution 2: Disable Redirects with CheckRedirect
Create an http.Client with the CheckRedirect field set to nil. This configures the client to not follow redirects.
import "net/http" func QueryURLWithoutRedirect(url string) (*http.Response, error) { client := &http.Client{ CheckRedirect: nil, } return client.Get(url) }
Further Considerations
While both solutions provide the desired functionality, the first approach may experience performance issues under high load, as it may reuse connections that are closed prematurely.
To ensure that each query opens a new connection with the second approach, you can create a new http.Client for each request in a loop. However, this may not be necessary, as Go automatically closes idle connections after a certain period.
Ultimately, the choice of approach depends on your specific performance requirements and the behavior you desire in a real-world scenario.
The above is the detailed content of How Can I Query URLs in Go Without Following Redirects?. For more information, please follow other related articles on the PHP Chinese website!