Disabling Automatic Redirects in Go HTTP Client
The Go HTTP client automatically follows HTTP redirects when an API endpoint returns an HTTP 302 redirect with an HTTP Location header. This behavior may be undesirable in certain scenarios, such as when you need to capture the HTTP Location header for later processing.
A common approach to disable automatic redirects involves overriding the client's CheckRedirect function. However, this solution may feel like a hack as it treats HTTP redirects as errors, which they are not.
A more elegant solution is to use the http.Transport to configure the client's behavior:
import ( "net/http" ) // Create a custom round-trip transport transport := &http.Transport{ DisableKeepAlives: true, } // Create an HTTP client with the custom transport client := &http.Client{ Transport: transport, }
In this setup, the DisableKeepAlives field is set to true which prevents the client from keeping persistent connections, avoiding the need to intercept redirects.
Alternatively, you can use the following code to disable redirects explicitly:
client := &http.Client{ CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, }
With this code, the HTTP package automatically recognizes that redirects should not be followed, but does not throw any errors. This allows you to make HTTP requests with Basic Authentication while disabling automatic redirects without resorting to complex error handling.
The above is the detailed content of How to Disable Automatic Redirects in the Go HTTP Client?. For more information, please follow other related articles on the PHP Chinese website!