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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.