Control Redirects With CheckRedirect

Decide per request whether the client follows a redirect by installing CheckRedirect, counting the chain length and stopping with http.ErrUseLastResponse.

GoSecurity Boundaries

Code

snippet
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

func main() {
	// 三跳链:/login -> /step1 -> /step2
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Path {
		case "/login":
			http.Redirect(w, r, "/step1", http.StatusSeeOther)
		case "/step1":
			http.Redirect(w, r, "/step2", http.StatusSeeOther)
		default:
			fmt.Fprintln(w, "landed on "+r.URL.Path)
		}
	}))
	defer server.Close()

	client := &http.Client{
		// CheckRedirect 在每次跟随前被调用:via 是已经发出的请求链
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			fmt.Printf("redirect #%d -> %s\n", len(via), req.URL.Path)
			if len(via) > 1 {
				// 停止跟随:把最近一次响应原样交回调用方
				return http.ErrUseLastResponse
			}
			return nil
		},
	}

	resp, err := client.Get(server.URL + "/login")
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	fmt.Println("final status:", resp.StatusCode)
	fmt.Println("final location:", resp.Header.Get("Location"))
}

What the code does

Structurally, expect the function main and nothing else.

Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly. The cleanup call is deferred to function exit — success, early return, and panic all covered.

What to watch for

  • No package manager involved — every call resolves to a built-in API.
  • Errors are ordinary return values; skipping the err check means using a zero value silently.

Using it

Running the file prints labeled results such as redirect #, final status:, final location: — each operation’s effect is visible in the output.

Key statements

if err != nil {
panic(err)
}
defer resp.Body.Close()
defer server.Close()

Interactive Tools for This Topic

FAQ

Is there exception handling?
As returned `error` values — 1 site in the snippet check `err` before using other results.
What does Control Redirects With CheckRedirect print when run?
Run it as a complete program — the output lines carry labels such as `redirect #`, `final status:`, `final location:`.