go 48 lines · 7 steps

A deadline-enforcing HTTP middleware in Go

A middleware that races each request against a timeout, logging slow ones and cutting off those that run over.

Explained by highlit
1package middleware
2 
3import (
4 "context"
5 "log/slog"
6 "net/http"
7 "time"
8)
9 
10func DeadlineGuard(timeout, slowThreshold time.Duration, logger *slog.Logger) func(http.Handler) http.Handler {
11 return func(next http.Handler) http.Handler {
12 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
13 deadline := time.Now().Add(timeout)
14 ctx, cancel := context.WithDeadline(r.Context(), deadline)
15 defer cancel()
16 
17 start := time.Now()
18 done := make(chan struct{})
19 
20 go func() {
21 next.ServeHTTP(w, r.WithContext(ctx))
22 close(done)
23 }()
24 
25 select {
26 case <-done:
27 elapsed := time.Since(start)
28 if elapsed > slowThreshold {
29 logger.Warn("slow request",
30 "method", r.Method,
31 "path", r.URL.Path,
32 "elapsed_ms", elapsed.Milliseconds(),
33 "threshold_ms", slowThreshold.Milliseconds(),
34 )
35 }
36 case <-ctx.Done():
37 if ctx.Err() == context.DeadlineExceeded {
38 logger.Error("request deadline exceeded",
39 "method", r.Method,
40 "path", r.URL.Path,
41 "timeout_ms", timeout.Milliseconds(),
42 )
43 http.Error(w, "request timed out", http.StatusGatewayTimeout)
44 }
45 }
46 })
47 }
48}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Passing a deadline through the request context lets downstream handlers cooperatively cancel their own work.
  2. 2Racing a done channel against ctx.Done() with select lets you react the moment either the handler or the deadline wins.
  3. 3Once a timeout response is sent the handler goroutine keeps running, so real cancellation depends on downstream code respecting the context.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A deadline-enforcing HTTP middleware in Go — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code