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
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
go
package handlers import ( "net/http"
Serving embedded static meta files in Gin
embedding
static assets
http caching
Intermediate
6 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
python
from functools import wraps import asyncio from fastapi import APIRouter, FastAPI, Request
Per-route request timeouts in FastAPI
decorators
async
timeouts
Intermediate
6 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
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.