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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Passing a deadline through the request context lets downstream handlers cooperatively cancel their own work.
- 2Racing a done channel against ctx.Done() with select lets you react the moment either the handler or the deadline wins.
- 3Once a timeout response is sent the handler goroutine keeps running, so real cancellation depends on downstream code respecting the context.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-deadline-enforcing-http-middleware-in-go-explained-go-ccd8/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.