Leveraging Go HTTP Client to Disable Automatic Redirects
In Go programming, handling HTTP redirects is essential when building RESTful API clients. However, there are scenarios where automatic redirect handling is undesirable. This question explores an alternative approach to prevent the Go HTTP client from automatically following redirects.
The initial solution provided in the question highlights a custom implementation of the CheckRedirect function, forcing HTTP redirects to be treated as errors. While technically effective, it feels unnatural to classify redirects as failures.
To address this issue, the answer presents a more elegant solution: modifying the CheckRedirect function to return http.ErrUseLastResponse. This signals to the HTTP package that redirects should not be followed, without triggering error handling.
Here is the updated code:
client := &http.Client{ CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, }
With this modification, the HTTP client will ignore redirects and return the most recent response with its body still accessible. The comment in the source code clarifies:
As a special case, if CheckRedirect returns ErrUseLastResponse, then the most recent response is returned with its body unclosed, along with a nil error.
As a result, you can handle redirects manually within your script, providing greater flexibility and control over the HTTP workflow. By leveraging this technique, you can interact with REST APIs that return redirects while maintaining the desired level of customization.
The above is the detailed content of How Can I Prevent Go's HTTP Client from Automatically Following Redirects?. For more information, please follow other related articles on the PHP Chinese website!