client := &http.Client{ CheckRedirect: func(req *http.Request, via []*http.Request) error { // Print the URL of the redirected request fmt.Println("Redirected to:", req.URL.String()) // Allow a maximum of 5 redirects if len(via) >= 5 { return errors.New("too many redirects") } return nil }, }
func main() { resp, err := http.Get("http://example.com") if err != nil { log.Fatal(err) } defer resp.Body.Close() // Create a new client with a custom CheckRedirect function client := &http.Client{ CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse // Cancel redirects }, } // Create a new request to follow the redirect req, err := http.NewRequest("GET", resp.Header.Get("Location"), nil) if err != nil { log.Fatal(err) } // Use the custom client to send the request resp, err = client.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() // Handle the response fmt.Println(resp.Status) }In this example, we first send a GET request to `example.com` which responds with a redirect response. We then create a new client with a `CheckRedirect` function that cancels redirects. We also create a new request to follow the redirect using the `Location` header from the original response. Finally, we use the custom client to send the request and handle the response. In both examples, we are using the `net/http` package in Go.