These are the notes for Go episode 64. Raju's server needs a log line for every request, a polite answer when a handler has a bug, and a key check on the admin pages. Pasting the same code into every handler fails (someone always forgets), so we invent middleware: a function that takes an http.Handler and returns a new http.Handler around it. On the way we capture the status code by wrapping the ResponseWriter, fix the Flush it breaks with Unwrap and http.ResponseController, chain middleware in the right order, turn panics into 500, carry a request ID in the request's context, check an API key, answer CORS preflights, and put a time limit on slow handlers with http.TimeoutHandler.
All outputs are from real runs (Go 1.24.7, linux/amd64). Durations, request IDs, ports and log timestamps change between runs.
Facts and sources
All from the Go documentation of the installed toolchain (go doc, Go 1.24.7) and the API files in $(go env GOROOT)/api:
go doc net/http.Handler: "If ServeHTTP panics, the server (the caller of ServeHTTP) assumes that the effect of the panic was isolated to the active request. It recovers the panic, logs a stack trace to the server error log, and either closes the network connection or sends an HTTP/2 RST_STREAM, depending on the HTTP protocol."go doc net/http.NewResponseController: "The ResponseWriter should be the original value passed to the [Handler.ServeHTTP] method, or have an Unwrap method returning the original ResponseWriter." and "If the ResponseWriter does not support a method, ResponseController returns an error matching ErrNotSupported."ErrNotSupportedis&ProtocolError{"feature not supported"}.NewResponseControlleris listed inapi/go1.20.txt(added in Go 1.20).go doc net/http.TimeoutHandler: "if a call runs for longer than its time limit, the handler responds with a 503 Service Unavailable error and the given message in its body" and "TimeoutHandler supports the Pusher interface but does not support the Hijacker or Flusher interfaces."go doc context.WithValue: "Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions. The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context. Users of WithValue should define their own types for keys."go doc crypto/rand.Text: "Text returns a cryptographically random string using the standard RFC 4648 base32 alphabet"; it is listed inapi/go1.24.txt(new in Go 1.24).- Everything else is from the real runs below.
The copy-paste problem
Logging means writing a line about each thing a program does (here: each request, with its method, path and duration) so you can look back later. Real-life example: the owner says "write every order in the register". Each cook writes their own line, a new cook forgets, and the bill orders never reach the register.
The obvious attempt: paste the same timing and logging lines into every handler.
package main
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"os"
"time"
)
func menu(w http.ResponseWriter, r *http.Request) {
start := time.Now() // copy...
defer func() { log.Println(r.Method, r.URL.Path, time.Since(start)) }() // ...paste
fmt.Fprintln(w, "chai ₹20")
}
func order(w http.ResponseWriter, r *http.Request) {
start := time.Now()
defer func() { log.Println(r.Method, r.URL.Path, time.Since(start)) }()
fmt.Fprintln(w, "order placed")
}
func bill(w http.ResponseWriter, r *http.Request) { // someone forgot to paste
fmt.Fprintln(w, "₹45")
}
func main() {
log.SetOutput(os.Stdout)
log.SetFlags(0)
mux := http.NewServeMux()
mux.HandleFunc("GET /menu", menu)
mux.HandleFunc("POST /order", order)
mux.HandleFunc("GET /bill", bill)
for _, t := range []struct{ m, p string }{{"GET", "/menu"}, {"POST", "/order"}, {"GET", "/bill"}} {
mux.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(t.m, t.p, nil))
}
}
Real output:
GET /menu 3.201µs
POST /order 1.454µs
Three requests went in, two log lines came out: GET /bill was never logged because nobody pasted the lines there. With fifty handlers, someone always forgets, and every change to the log format means fifty edits.
Middleware: the signature func(http.Handler) http.Handler
Middleware is code that runs before (and/or after) every handler, without the handler knowing. Real-life example: the security check at an airport. Every passenger passes the same check before any gate; the gates don't each do their own.
| Airport | Go |
|---|---|
| security check before every gate | middleware |
| the gate and the plane | the handler, called with next.ServeHTTP(w, r) |
| a checkpoint: in one side, out the other | the signature func(http.Handler) http.Handler |
A signature is a function's parameter and result types. Middleware always has the same one: it takes the next handler and returns a new handler that wraps it. Inside, it can do work before next.ServeHTTP, work after it, or stop the request by not calling next at all.
package main
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"os"
"time"
)
// logging is middleware: it takes a Handler and returns a new Handler around it.
func logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r) // run the real handler
log.Println(r.Method, r.URL.Path, time.Since(start))
})
}
func main() {
log.SetOutput(os.Stdout)
log.SetFlags(0)
mux := http.NewServeMux()
mux.HandleFunc("GET /menu", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "chai ₹20") })
mux.HandleFunc("POST /order", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "order placed") })
mux.HandleFunc("GET /bill", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "₹45") })
h := logging(mux) // wrap ALL routes at once
for _, t := range []string{"GET /menu", "POST /order", "GET /bill", "GET /menu/9"} {
var m, p string
fmt.Sscan(t, &m, &p)
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(m, p, nil))
}
}
Real output:
GET /menu 4.145µs
POST /order 1.814µs
GET /bill 1.266µs
GET /menu/9 2.845µs
logging returns http.HandlerFunc(...) of a closure (a function literal that remembers next, episode 10). We wrap the whole mux once with h := logging(mux), so every route is logged, including /bill, and no handler changed. But GET /menu/9 was a 404 and the log line can't show that.
The obvious attempt to log the status
package main
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"os"
"time"
)
// logging is middleware: it takes a Handler and returns a new Handler around it.
func logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r) // run the real handler
log.Println(r.Method, r.URL.Path, w.Status(), time.Since(start))
})
}
func main() {
log.SetOutput(os.Stdout)
log.SetFlags(0)
mux := http.NewServeMux()
mux.HandleFunc("GET /menu", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "chai ₹20") })
mux.HandleFunc("POST /order", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "order placed") })
mux.HandleFunc("GET /bill", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "₹45") })
h := logging(mux) // wrap ALL routes at once
for _, t := range []string{"GET /menu", "POST /order", "GET /bill", "GET /menu/9"} {
var m, p string
fmt.Sscan(t, &m, &p)
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(m, p, nil))
}
}
Real compiler output:
# command-line-arguments
./main.go:17:45: w.Status undefined (type http.ResponseWriter has no field or method Status)
An http.ResponseWriter is an interface with only three methods: Header(), Write([]byte) and WriteHeader(int). It sends the status and forgets it.
Capturing the status: wrapping the ResponseWriter
Real-life example: a clerk takes the reply pad before the cook, copies down the stamp ("done", "sold out"), and passes the pad on unchanged. At the end he reads his note and writes the register line.
We write our own type that wraps the real ResponseWriter: it embeds it (episode 23), so Header and Write pass straight through, and it overrides WriteHeader to remember the code.
package main
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"os"
"time"
)
// statusRecorder wraps a ResponseWriter and remembers the status code.
type statusRecorder struct {
http.ResponseWriter // embedded: all other methods pass straight through
status int
}
func (s *statusRecorder) WriteHeader(code int) {
s.status = code
s.ResponseWriter.WriteHeader(code)
}
// func (s *statusRecorder) Unwrap() http.ResponseWriter { return s.ResponseWriter }
func logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, status: 200} // 200 unless told otherwise
next.ServeHTTP(rec, r)
log.Println(r.Method, r.URL.Path, rec.status, time.Since(start))
})
}
func main() {
log.SetOutput(os.Stdout)
log.SetFlags(0)
mux := http.NewServeMux()
mux.HandleFunc("GET /menu", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "chai ₹20") })
mux.HandleFunc("GET /live", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "data: chai brewing")
err := http.NewResponseController(w).Flush() // send it now
fmt.Println(" flush error:", err)
})
h := logging(mux)
for _, p := range []string{"/menu", "/menu/9", "/live"} {
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", p, nil))
}
}
Real output:
GET /menu 200 4.173µs
GET /menu/9 404 2.933µs
flush error: feature not supported
GET /live 200 7.004µs
- The status starts at 200 because a handler that never calls
WriteHeadergets200 OKon its firstWrite. /menu/9is now logged as 404.- But
/liveprintedflush error: feature not supported. Flushing means sending what's written so far to the client right now instead of when the handler returns (needed for streaming, episode 62). The realResponseWritercan flush; our wrapper type only has the methods we gave it, so it hid that ability.
The fix: Unwrap + http.ResponseController
http.ResponseController (Go 1.20+) is a helper that controls a response: Flush, SetReadDeadline, SetWriteDeadline, EnableFullDuplex, Hijack. If the writer it is given doesn't have the method, it calls the writer's Unwrap() http.ResponseWriter method and tries the writer inside. Uncommenting one line:
package main
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"os"
"time"
)
// statusRecorder wraps a ResponseWriter and remembers the status code.
type statusRecorder struct {
http.ResponseWriter // embedded: all other methods pass straight through
status int
}
func (s *statusRecorder) WriteHeader(code int) {
s.status = code
s.ResponseWriter.WriteHeader(code)
}
func (s *statusRecorder) Unwrap() http.ResponseWriter { return s.ResponseWriter }
func logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, status: 200} // 200 unless told otherwise
next.ServeHTTP(rec, r)
log.Println(r.Method, r.URL.Path, rec.status, time.Since(start))
})
}
func main() {
log.SetOutput(os.Stdout)
log.SetFlags(0)
mux := http.NewServeMux()
mux.HandleFunc("GET /menu", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "chai ₹20") })
mux.HandleFunc("GET /live", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "data: chai brewing")
err := http.NewResponseController(w).Flush() // send it now
fmt.Println(" flush error:", err)
})
h := logging(mux)
for _, p := range []string{"/menu", "/menu/9", "/live"} {
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", p, nil))
}
}
Real output:
GET /menu 200 4.098µs
GET /menu/9 404 2.968µs
flush error: <nil>
GET /live 200 5.73µs
flush error: <nil>: flushing works again and the statuses are still logged.
Rules for a ResponseWriter wrapper:
- Embed
http.ResponseWriter. - Override
WriteHeader(andWriteif you need the byte count) and call the inner one. - Start the status at 200.
- Add
Unwrap() http.ResponseWriter. - In handlers, use
http.NewResponseController(w).Flush()instead ofw.(http.Flusher), so wrappers don't break streaming.
Chaining middleware
Real-life example: at the airport you pass the ticket and ID check, then the bag scan, then the boarding pass at the gate; coming back you walk out through them in reverse.
Chaining means wrapping middleware inside each other: a(b(c(handler))). A small chain helper makes the order readable. It takes a variadic list (mws ...Middleware, episode 9) and wraps from the last backwards, so the first one listed is the outermost and runs first.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
type Middleware func(http.Handler) http.Handler
// chain(h, a, b, c) = a(b(c(h))): the first one listed runs first.
func chain(h http.Handler, mws ...Middleware) http.Handler {
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
func step(name string) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println(name, "-> in")
next.ServeHTTP(w, r)
fmt.Println(name, "<- out")
})
}
}
func main() {
menu := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println(" menu handler")
})
h := chain(menu, step("logging"), step("recover"), step("auth"))
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/menu", nil))
}
Real output:
logging -> in
recover -> in
auth -> in
menu handler
auth <- out
recover <- out
logging <- out
In order going in, in reverse coming out. A typical order:
| Position | Middleware | Why there |
|---|---|---|
| outermost | request ID | everything inside can read the ID |
| next | logging | times and logs everything, including 500s from the recoverer |
| next | recover | catches panics from everything inside it |
| per route | auth, CORS, limits | only where needed |
| innermost | the handler | the real work |
Panic recovery middleware
A panic (episode 26) is what Go does when a program hits a bug it can't continue from, such as writing to a nil map; it unwinds the stack running deferred calls. recover, called in a deferred function, stops the unwinding and returns the panic's value.
Real-life example: a cook drops the pot. Without a manager, the waiter just walks away and the customer gets nothing. A shift manager steps in: "sorry, something went wrong".
package main
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
)
func recoverer(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if v := recover(); v != nil { // a panic happened below us
log.Printf("panic in %s %s: %v", r.Method, r.URL.Path, v)
http.Error(w, "something went wrong", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
func main() {
var bills map[string]int // nil map: a bug
bill := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
bills["table 4"] = 45 // panics
fmt.Fprintln(w, "bill saved")
})
for _, h := range []http.Handler{bill, recoverer(bill)} {
srv := httptest.NewServer(h)
resp, err := http.Get(srv.URL + "/bill")
if err != nil {
fmt.Println("customer got:", err)
} else {
fmt.Println("customer got:", resp.Status)
resp.Body.Close()
}
srv.Close()
}
}
Real output (stderr and stdout together):
2026/11/13 11:28:54 http: panic serving 127.0.0.1:37494: assignment to entry in nil map
goroutine 22 [running]:
net/http.(*conn).serve.func1()
/usr/local/go1.24.7/src/net/http/server.go:1947 +0xbe
panic({0x6e4620?, 0x9bff90?})
/usr/local/go1.24.7/src/runtime/panic.go:792 +0x132
main.main.func1({0x7ba150, 0xc0000000e0}, 0x0?)
main.go:25 +0x38
net/http.HandlerFunc.ServeHTTP(0x46d9b9?, {0x7ba150?, 0xc0000000e0?}, 0xc000197b70?)
/usr/local/go1.24.7/src/net/http/server.go:2294 +0x29
net/http.serverHandler.ServeHTTP({0xc00011fc50?}, {0x7ba150?, 0xc0000000e0?}, 0x1?)
/usr/local/go1.24.7/src/net/http/server.go:3301 +0x8e
net/http.(*conn).serve(0xc00016c3f0, {0x7ba550, 0xc00011fb30})
/usr/local/go1.24.7/src/net/http/server.go:2102 +0x625
created by net/http.(*Server).Serve in goroutine 20
/usr/local/go1.24.7/src/net/http/server.go:3454 +0x485
customer got: Get "http://127.0.0.1:34797/bill": EOF
2026/11/13 11:28:54 panic in GET /bill: assignment to entry in nil map
customer got: 500 Internal Server Error
- Without the recoverer,
net/httpitself recovered the panic (the server keeps running), loggedhttp: panic serving ...and a stack trace (the list of function calls that led to the panic, useful for developers), and closed the connection: the customer gotEOF(end of file: the connection closed with no reply). - With
recoverer: one clean log line and a real 500 Internal Server Error that the client can show or retry.
Request IDs, request-scoped values in context, and authentication
Real-life examples:
| At Raju's | In Go |
|---|---|
| a token number for each order ("token 47, your chai") | a request ID: a unique label for one request |
| the token stapled to the order slip | a context value: context.WithValue + r.WithContext |
| staff-only door: show your key card | authentication middleware: 401 if the key is wrong |
A request ID is put in every log line about a request and sent back in a header (X-Request-ID), so one request can be followed through all the logs. Handlers have a fixed signature, so we can't add an id parameter; instead we put it in the request's context (episode 51). Values stored there are request-scoped: they live exactly as long as this one request and travel with it.
Authentication means checking who is asking. Here: an API key in the Authorization header as Bearer <key> ("whoever bears this key may enter"). 401 Unauthorized means "who are you?" (no or wrong credentials); 403 Forbidden means "I know who you are, but you may not".
package main
import (
"context"
"crypto/rand"
"fmt"
"net/http"
"net/http/httptest"
)
type ctxKey string // our own key type: no clash with other packages' keys
const idKey ctxKey = "request-id"
func requestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := rand.Text()[:8] // a random ID for this request
w.Header().Set("X-Request-ID", id)
ctx := context.WithValue(r.Context(), idKey, id)
next.ServeHTTP(w, r.WithContext(ctx)) // pass the request on, with the ID inside
})
}
func requireKey(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer raju-secret" {
http.Error(w, "unauthorized", http.StatusUnauthorized) // 401: stop here
return
}
next.ServeHTTP(w, r)
})
}
func sales(w http.ResponseWriter, r *http.Request) {
id, _ := r.Context().Value(idKey).(string)
fmt.Fprintf(w, "today's sales ₹4,250 (request %s)\n", id)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /menu", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "chai ₹20") })
mux.Handle("GET /admin/sales", requireKey(http.HandlerFunc(sales))) // only this route
h := requestID(mux)
for _, auth := range []string{"", "Bearer raju-secret"} {
req := httptest.NewRequest("GET", "/admin/sales", nil)
req.Header.Set("Authorization", auth)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
fmt.Printf("auth=%-20q %d X-Request-ID=%s %s", auth, rec.Code, rec.Header().Get("X-Request-ID"), rec.Body)
}
}
Real output:
auth="" 401 X-Request-ID=KLGKWVUY unauthorized
auth="Bearer raju-secret" 200 X-Request-ID=C4BFSM5D today's sales ₹4,250 (request C4BFSM5D)
type ctxKey string: our own key type. Two packages that both use the plain string"request-id"would overwrite each other; values of different types never compare equal, so typed keys can't collide.context.WithValue(r.Context(), idKey, id)makes a new context carrying the ID;r.WithContext(ctx)makes a shallow copy of the request with that context;nextgets the copy.r.Context().Value(idKey).(string)reads it back with a type assertion (episode 22).requireKeywraps only/admin/sales;requestIDwraps the whole mux, so even the 401 reply carries anX-Request-ID.rand.Text()comes fromcrypto/rand(new in Go 1.24): cryptographically random base32 text.
CORS handling and http.TimeoutHandler
An origin is the scheme, host and port of a web page, like https://rajus-app.in. A request from a page on one origin to a server on another is cross-origin. Browsers don't let a page read cross-origin replies unless the server allows it with CORS (Cross-Origin Resource Sharing) headers:
| Header | Meaning |
|---|---|
Access-Control-Allow-Origin: https://rajus-app.in |
pages from this origin may read the reply |
Access-Control-Allow-Methods: GET, POST |
methods allowed (preflight reply) |
Access-Control-Allow-Headers: Content-Type |
request headers allowed (preflight reply) |
Vary: Origin |
tells caches the answer depends on the Origin header |
For "non-simple" requests (for example a JSON POST) the browser first sends a preflight: an OPTIONS request asking "may this origin use POST?". Real-life example: a visitor calls ahead before coming over. 204 No Content means success with no body.
http.TimeoutHandler(h, d, msg) runs h with a time limit d; if it takes longer it answers 503 Service Unavailable with msg. Real-life example: "if the dish isn't ready in ten minutes, tell the customer".
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"time"
)
// cors lets pages from one other site (Origin) call this API from a browser.
func cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Origin") == "https://rajus-app.in" {
w.Header().Set("Access-Control-Allow-Origin", "https://rajus-app.in")
w.Header().Set("Vary", "Origin")
}
if r.Method == http.MethodOptions { // the browser's "may I?" preflight
w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.WriteHeader(http.StatusNoContent) // 204: yes, and nothing else
return
}
next.ServeHTTP(w, r)
})
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("POST /order", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "order placed") })
mux.HandleFunc("GET /report", func(w http.ResponseWriter, r *http.Request) {
time.Sleep(2 * time.Second) // a slow report
fmt.Fprintln(w, "report")
})
h := cors(mux)
slow := http.TimeoutHandler(h, 500*time.Millisecond, "kitchen too slow, try again")
for _, t := range []struct{ method, path, origin string }{
{"OPTIONS", "/order", "https://rajus-app.in"},
{"POST", "/order", "https://rajus-app.in"},
{"POST", "/order", "https://evil.example"},
{"GET", "/report", ""},
} {
req := httptest.NewRequest(t.method, t.path, nil)
req.Header.Set("Origin", t.origin)
rec := httptest.NewRecorder()
slow.ServeHTTP(rec, req)
fmt.Printf("%-7s %-7s %-22q %d allow-origin=%q %s\n", t.method, t.path, t.origin, rec.Code,
rec.Header().Get("Access-Control-Allow-Origin"), strings.TrimSpace(rec.Body.String()))
}
}
Real output (/report came back after about half a second, not two):
OPTIONS /order "https://rajus-app.in" 204 allow-origin="https://rajus-app.in"
POST /order "https://rajus-app.in" 200 allow-origin="https://rajus-app.in" order placed
POST /order "https://evil.example" 200 allow-origin="" order placed
GET /report "" 503 allow-origin="" kitchen too slow, try again
- The preflight got 204 and the allow headers.
- The
POSTfromhttps://rajus-app.ingot theAccess-Control-Allow-Originheader, so a browser lets that page read it. - The
POSTfromhttps://evil.examplegot no allow header, so a browser hides the reply from that page, butorder placed, 200: the handler ran anyway. CORS is enforced by browsers only; scripts,curland servers ignore it. CORS is not authentication. Protect state-changing routes with real authentication on the server. /reporttook 2 s, soTimeoutHandleranswered 503 after 0.5 s. It does not supportFlusher, so don't wrap streaming routes with it.
Mini project: Raju's middleware stack
Build: requestID (header + context value), logging (request ID, method, path, status, duration), recoverer (500 + one log line with the request ID), requireKey only on /admin/ routes, a chain helper, and a table test for every route.
Full solution
main.go:
package main
import (
"context"
"crypto/rand"
"fmt"
"log"
"net/http"
"time"
)
type Middleware func(http.Handler) http.Handler
type ctxKey string
const idKey ctxKey = "request-id"
// RequestID returns the request ID stored in ctx, or "-".
func RequestID(ctx context.Context) string {
if id, ok := ctx.Value(idKey).(string); ok {
return id
}
return "-"
}
func chain(h http.Handler, mws ...Middleware) http.Handler {
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
type statusRecorder struct {
http.ResponseWriter
status int
}
func (s *statusRecorder) WriteHeader(code int) {
s.status = code
s.ResponseWriter.WriteHeader(code)
}
func (s *statusRecorder) Unwrap() http.ResponseWriter { return s.ResponseWriter }
func requestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := rand.Text()[:8]
w.Header().Set("X-Request-ID", id)
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), idKey, id)))
})
}
func logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rec, r)
log.Printf("%s %s %s %d %v", RequestID(r.Context()), r.Method, r.URL.Path, rec.status, time.Since(start))
})
}
func recoverer(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if v := recover(); v != nil {
log.Printf("%s panic: %v", RequestID(r.Context()), v)
http.Error(w, "something went wrong", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
func requireKey(key string) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer "+key {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
}
func Routes(key string) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /menu", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "chai ₹20")
})
mux.HandleFunc("GET /crash", func(w http.ResponseWriter, r *http.Request) {
var m map[string]int
m["x"] = 1 // a bug: panics
})
admin := requireKey(key)
mux.Handle("GET /admin/sales", admin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "sales ₹4,250 (request %s)\n", RequestID(r.Context()))
})))
// requestID outermost so the logger and the recoverer can both read the ID
return chain(mux, requestID, logging, recoverer)
}
func main() {
log.Println("Raju's server on http://localhost:8080/menu")
log.Fatal(http.ListenAndServe(":8080", Routes("raju-secret")))
}
main_test.go:
package main
import (
"net/http/httptest"
"testing"
)
func TestRoutes(t *testing.T) {
h := Routes("raju-secret")
for _, tc := range []struct {
path, auth string
want int
}{
{"/menu", "", 200},
{"/menu/9", "", 404},
{"/crash", "", 500},
{"/admin/sales", "", 401},
{"/admin/sales", "Bearer wrong", 401},
{"/admin/sales", "Bearer raju-secret", 200},
} {
req := httptest.NewRequest("GET", tc.path, nil)
if tc.auth != "" {
req.Header.Set("Authorization", tc.auth)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != tc.want {
t.Errorf("%s %q: got %d, want %d", tc.path, tc.auth, rec.Code, tc.want)
}
if len(rec.Header().Get("X-Request-ID")) != 8 {
t.Errorf("%s: no X-Request-ID", tc.path)
}
}
}
Real run:
$ go vet . && go test -count=1 -v .
=== RUN TestRoutes
2026/11/13 11:30:26 I7GUOEWI GET /menu 200 6.253µs
2026/11/13 11:30:26 H5QJBC33 GET /menu/9 404 3.999µs
2026/11/13 11:30:26 62BX4ACD panic: assignment to entry in nil map
2026/11/13 11:30:26 62BX4ACD GET /crash 500 16.237µs
2026/11/13 11:30:26 54SU5TAT GET /admin/sales 401 1.38µs
2026/11/13 11:30:26 PZCVKPGP GET /admin/sales 401 1.109µs
2026/11/13 11:30:26 VXA3DRL5 GET /admin/sales 200 1.976µs
--- PASS: TestRoutes (0.00s)
PASS
ok stack 0.003s
requestID is outermost so both the logger and the recoverer can read the ID; logging wraps recoverer, so the 500 from a panic is logged with its status. requireKey(key) is a function that returns a middleware, so it can take a parameter.
Common mistakes (and the real messages)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
w.Status() in a logger |
w.Status undefined (type http.ResponseWriter has no field or method Status) |
the writer doesn't remember the status | wrap w, override WriteHeader |
a wrapper without Unwrap |
flush error: feature not supported |
the wrapper hides Flush |
add Unwrap() http.ResponseWriter; use http.NewResponseController |
| status field starting at 0 | logs 0 for normal replies |
handlers that never call WriteHeader send 200 |
start at http.StatusOK |
forgetting next.ServeHTTP |
an empty 200 reply |
the chain stops | call next, or reply and return |
no return after rejecting |
the protected handler still runs | the middleware continues | http.Error(...) then return |
| no recover middleware | client: EOF; server: http: panic serving ... + stack trace |
net/http closes the connection |
recover → 500 |
setting a header after next |
the header never arrives (X-Shop="") |
the handler already sent headers | set headers before next |
| plain string context keys | values overwritten by another package | keys of the same type and value collide | type ctxKey string (unexported) |
| treating CORS as security | the evil origin's POST still ran (order placed) |
only browsers obey CORS | authenticate on the server |
TimeoutHandler around streaming |
flushing fails | it doesn't support Flusher |
per-request contexts / deadlines instead |
Practice
- Write a middleware that adds
X-Shop: Rajuto every response. Does it matter whether you set the header before or afternext.ServeHTTP? - In the mini project, swap the order to
chain(mux, requestID, recoverer, logging). What does the log show for/crash? - Write
maxBody(n int64) Middlewarethat limits every request body withhttp.MaxBytesReader(episode 62). - Why does
requireKeyanswer 401 and not 403 for a missing key?
Solutions
1. Before. Real run of both versions against a handler that writes a body:
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
func late(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
w.Header().Set("X-Shop", "Raju") // after the handler wrote the body
})
}
func early(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Shop", "Raju") // before
next.ServeHTTP(w, r)
})
}
func main() {
menu := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "chai ₹20") })
for _, m := range []func(http.Handler) http.Handler{late, early} {
h := m(menu)
srv := httptest.NewServer(h)
resp, _ := http.Get(srv.URL)
resp.Body.Close()
fmt.Printf("X-Shop=%q\n", resp.Header.Get("X-Shop"))
srv.Close()
}
}
X-Shop=""
X-Shop="Raju"
After next the handler has already written the body, which sends the headers, so the late Set changes nothing.
2. The panic happens inside logging, unwinds through it (its log line after next.ServeHTTP never runs) and is caught by recoverer outside it: you get the panic: line but no access-log line for /crash. Keep logging outside recoverer.
3.
func maxBody(n int64) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, n)
next.ServeHTTP(w, r)
})
}
}
4. 401 Unauthorized means the client hasn't proved who it is (no or wrong credentials). 403 Forbidden is for a known client that isn't allowed, for example a logged-in waiter asking for the sales report.
Quick quiz
1. h := chain(handler, step("A"), step("B")), where step prints "in", calls next, then prints "out". What's printed? (From the video.)
A. A in, B in, handler, B out, A out · B. B in, A in, handler, A out, B out · C. A in, A out, B in, B out, handler · D. handler, A, B
Answer
A. chain wraps from the last backwards, so the first listed is outermost: in order going in, reverse coming out.
2. What does a client get when a handler panics and there is no recover middleware (HTTP/1.1)?
Answer
No response: the server recovers the panic, logs http: panic serving ... with a stack trace, and closes the connection, so the client sees EOF.
3. Does a missing Access-Control-Allow-Origin header stop the request from reaching your handler?
Answer
No. The handler runs; only the browser refuses to show the reply to the page. CORS is not authentication.
Interview questions
- What is middleware in Go? A function
func(http.Handler) http.Handlerthat wraps a handler to add behaviour (logging, recovery, auth) before and/or after it, for many routes at once. - How do you log the response status in middleware? Wrap the
ResponseWriterin a type that embeds it and overridesWriteHeader; start at 200; addUnwrap. - Why add
Unwrapto a ResponseWriter wrapper? Sohttp.ResponseControllercan reach the original writer'sFlush, deadlines andHijack; otherwise you getfeature not supported. - In which order do chained middleware run? The outermost first on the way in, and last on the way out.
- Doesn't
net/httpalready recover panics? It recovers per request so the server survives, but logs a stack trace and drops the connection; a recover middleware sends a proper 500. - How do you pass a request ID to handlers?
context.WithValuewith an unexported key type,r.WithContext, and read it withr.Context().Value(key). - What should and shouldn't go in context values? Request-scoped data (request ID, authenticated user, trace info); not optional parameters, configuration or dependencies.
- What is a CORS preflight and does CORS protect your API? An
OPTIONSrequest the browser sends to ask permission; CORS only controls what browsers let pages read, it doesn't stop requests, so it's not a security boundary. - What does
http.TimeoutHandlerdo and what's its limitation? Gives a handler a time limit and answers 503 with a message; it doesn't supportFlusherorHijacker.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Logging | writing a line about each thing the program does | GET /menu 200 4.4µs |
| Middleware | code that wraps handlers, running before/after them | logging(mux) |
| Signature | a function's parameter and result types | func(http.Handler) http.Handler |
next |
the handler a middleware wraps | next.ServeHTTP(w, r) |
| Closure | a function literal that remembers outer variables | the HandlerFunc inside logging remembers next |
http.HandlerFunc |
adapter: function → Handler | http.HandlerFunc(func(w, r) {...}) |
| Logging middleware | logs every request in one place | method, path, status, duration |
| Status code | number saying how a request went | 200, 204, 401, 404, 500, 503 |
http.ResponseWriter |
interface a handler writes the reply to | Header, Write, WriteHeader |
| Wrapping a ResponseWriter | your type around the real writer | statusRecorder |
| Embedding | a field without a name; its methods are promoted | http.ResponseWriter inside statusRecorder |
| Flush | send what's written so far right now | streaming, server-sent events |
Unwrap |
method returning the writer inside a wrapper | func (s *statusRecorder) Unwrap() http.ResponseWriter |
http.ResponseController |
helper to Flush, set deadlines, Hijack (Go 1.20+) | http.NewResponseController(w).Flush() |
http.ErrNotSupported |
"feature not supported" | wrapper without Unwrap |
| Chaining | wrapping middleware inside each other | chain(h, logging, recover, auth) |
| Variadic parameter | takes any number of arguments | mws ...Middleware |
| Outermost | the middleware that runs first | the first in chain(...) |
| Panic | a run-time failure that unwinds the stack | assignment to entry in nil map |
recover |
stops a panic inside a deferred function | if v := recover(); v != nil |
| Panic recovery middleware | turns a panic into a 500 | recoverer |
| Stack trace | list of function calls that led to a panic | goroutine 22 [running]: ... |
EOF |
end of file: the connection closed with no reply | Get "...": EOF |
| 500 Internal Server Error | the server failed | after a recovered panic |
| Request ID | unique label for one request | X-Request-ID: SXPZRRRP |
| Request ID middleware | creates the ID, sets the header, stores it in the context | requestID |
| Context | per-request carrier of deadlines, cancellation and values | r.Context() |
| Request-scoped value | data that lives exactly as long as one request | the request ID, the logged-in user |
context.WithValue |
a new context carrying one key/value | context.WithValue(ctx, idKey, id) |
| Typed context key | an own type for keys so they can't collide | type ctxKey string |
r.WithContext |
shallow copy of a request with a new context | next.ServeHTTP(w, r.WithContext(ctx)) |
| Type assertion | gets the concrete value out of an interface | .Value(idKey).(string) |
crypto/rand.Text |
random base32 text (Go 1.24) | rand.Text()[:8] |
| Authentication | checking who is asking | API key in Authorization |
| Authentication middleware | rejects requests without valid credentials | requireKey |
Authorization header |
carries credentials | Authorization: Bearer raju-secret |
| Bearer token | "whoever bears this key may enter" | Bearer raju-secret |
| 401 Unauthorized | no or wrong credentials | missing key |
| 403 Forbidden | known client, not allowed | a waiter asking for sales |
| Origin | scheme + host + port of a page | https://rajus-app.in |
| Cross-origin request | a page calling another origin | rajus-app.in → api server |
| CORS | Cross-Origin Resource Sharing: headers that let pages read cross-origin replies | Access-Control-Allow-Origin |
| Preflight | the browser's OPTIONS "may I?" request |
OPTIONS /order |
Vary: Origin |
the reply depends on the Origin header (for caches) |
set with the allow-origin header |
| 204 No Content | success with no body | preflight reply |
http.TimeoutHandler |
runs a handler with a time limit | http.TimeoutHandler(h, 500*time.Millisecond, "kitchen too slow, try again") |
| 503 Service Unavailable | the server can't answer now | the timed-out /report |
httptest.NewRecorder |
fake ResponseWriter for tests | rec.Code |
Summary
- Middleware is
func(http.Handler) http.Handler: write cross-cutting code (logging, recovery, auth) once for every route. - To see the status, wrap the
ResponseWriter(embed it, overrideWriteHeader, start at 200) and addUnwrapsohttp.ResponseControllercan still flush. - Chains run outermost first and return in reverse: request ID → logging → recover → per-route auth → handler.
- A recover middleware turns a panic into a 500 instead of a dropped connection (
EOF). - Carry request-scoped values like a request ID in the context under a typed key.
- Auth middleware stops requests with 401; CORS only tells browsers what pages may read, it is not authentication.
http.TimeoutHandleranswers 503 after a time limit (noFlusher).
Next episode: Building a REST API: REST principles, resource and URL design, JSON request decoding and validation, consistent error responses, status codes, pagination, filtering and versioning.