Home > Backend Development > Golang > How Can I Prevent Redirects with the Go HTTP Client?

How Can I Prevent Redirects with the Go HTTP Client?

DDD
Release: 2024-12-21 06:44:13
Original
574 people have browsed it

How Can I Prevent Redirects with the Go HTTP Client?

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template