Home > Backend Development > Golang > How Can I Prevent Go's HTTP Client from Automatically Following Redirects?

How Can I Prevent Go's HTTP Client from Automatically Following Redirects?

Linda Hamilton
Release: 2025-01-04 01:53:39
Original
808 people have browsed it

How Can I Prevent Go's HTTP Client from Automatically Following Redirects?

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
    },
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template