Wrap Slow Handlers With TimeoutHandler

Give slow handlers a hard deadline with http.TimeoutHandler, which returns 503 with a custom message and throws away the late response entirely.

GoResilience

Code

snippet
package main

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

func main() {
	// 慢 handler:100ms 后才响应
	slow := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		time.Sleep(100 * time.Millisecond)
		fmt.Fprintln(w, "done")
	})

	// TimeoutHandler:超过 10ms 就回 503 与自定义提示,
	// 慢 handler 迟到的响应整体丢弃
	wrapped := http.TimeoutHandler(slow, 10*time.Millisecond, "handler timed out")
	server := httptest.NewServer(wrapped)
	defer server.Close()

	resp, err := http.Get(server.URL)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	fmt.Println("status:", resp.StatusCode)
	fmt.Printf("body: %s\n", string(body))
}

Inside the snippet

Wrap Slow Handlers With TimeoutHandler reduces to the function main.

Every err != nil branch (1 site) calls panic(err) — the run stops at the first failure instead of continuing in a broken state. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.

Points of care

  • Failures abort via panic(err) — nothing is returned for the caller to check, and nothing in the snippet recovers.

Putting it to use

The run emits 2 labeled sections — status:, body: — one per step.

Core lines

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

Interactive Tools for This Topic

FAQ

How are errors reported?
By aborting: each of the 1 `err != nil` branches calls `panic(err)`, so a failure stops the program at the point it is detected.
What does Wrap Slow Handlers With TimeoutHandler print when run?
Invoke the file as-is — the `status:`, `body:` prefixes identify which step printed each line.