Not Following Redirects with the Go HTTP Client
When interacting with REST APIs that return redirect responses, modifying the behavior of the Go HTTP client to ignore redirects can be necessary for specific use cases. Here's a simple and effective way to achieve this functionality:
The http.Client's CheckRedirect function takes precedence over the default redirect-following behavior. By customizing this function, you can determine when redirects should be followed. To prevent automatic redirection, provide an alternative implementation:
CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }
This configuration informs the HTTP package to avoid redirect operations. It returns http.ErrUseLastResponse, which instructs the package to utilize the latest response with the body still accessible.
In your example, update the client configuration as follows:
client := &http.Client{ CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, }
By setting this configuration, your script will successfully establish a connection to the endpoint, retrieve the HTTP Location header for further processing, and avoid being redirected to the new resource. This method provides a more elegant and error-free approach compared to alternative solutions that force error handling.
The above is the detailed content of How Can I Prevent Redirects with the Go HTTP Client?. For more information, please follow other related articles on the PHP Chinese website!