Skip to content

Lesson 3 of 9 · 26m

Middleware Is a Cost Center: Make It Earn Its Keep

Compose request logging, auth, recovery, headers, and request identity without creating hidden control flow or ordering bugs.

Middleware is where Go services quietly become impossible to reason about. Each layer looks harmless. Ten layers later nobody knows whether compression happens before logging, whether auth sees the original path, or which layer swallowed a panic. Middleware is not architecture. It is cross-cutting plumbing, and plumbing deserves restraint.

The shape is simple — ordering is not

Go middleware wraps a handler:

func middleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        next.ServeHTTP(w, r)
    })
}

Composition order matters because wrappers execute outside-in:

handler := chain(
    recoverer,
    requestID,
    accessLog,
    securityHeaders,
    authn,
)(mux)

If recoverer is outermost, it catches panics beneath it. If access logging sits inside authentication, rejected requests may never be logged. There is no universal correct order; there is only an order you can explain.

Capture response metadata without lying

Access logs need status and bytes, but ResponseWriter does not expose them:

type statusWriter struct {
    http.ResponseWriter
    status int
    bytes  int
}

func (w *statusWriter) WriteHeader(status int) {
    w.status = status
    w.ResponseWriter.WriteHeader(status)
}

Be careful: wrapping can hide optional interfaces such as http.Flusher, http.Hijacker, and io.ReaderFrom. Streaming and websockets expose this mistake quickly.

Panic recovery is containment, not a fix

Recovery prevents one bad request from killing the process, but it does not make the defect acceptable:

defer func() {
    if rec := recover(); rec != nil {
        slog.Error("panic", "panic", rec, "path", r.URL.Path)
        http.Error(w, "internal error", http.StatusInternalServerError)
    }
}()

Do not recover in domain code as control flow. Invariant panics should stay loud in development and tests.

Context is for request scope, not a junk drawer

context.Context carries cancellation, deadlines, request IDs, and authenticated principals. It is not where database handles or random feature state belong:

type ctxKey string
const principalKey ctxKey = "principal"

Use small typed keys and accessor functions. Middleware writing context values must run before handlers that read them — obvious, until a rushed diff proves otherwise.

Keep business authorization out of middleware

Middleware should enforce platform policy: identity, logging, rate limits, headers, compression, panic containment. Once middleware decides whether this customer can edit that order, object authorization has escaped the domain boundary and will be applied inconsistently.

Field notes

  • Write a one-line ordering contract in server setup; future you will read it during an incident.
  • Do not log Authorization headers, cookies, or full request bodies in access middleware.
  • Compression can break SSE and websockets. Test streaming explicitly.
  • Security headers are useful, but they do not replace authorization or output encoding.

Was this lesson helpful?

Sign in to rate