Backend Development

Middleware

Wrap HTTP handlers for shared behaviour while preserving correctness and clear ordering.

What you will learn

By the end of this lesson, you will be able to:

  • write middleware using func(http.Handler) http.Handler;
  • compose middleware in a deliberate order;
  • carry small request-scoped values through context;
  • record status codes without breaking response behaviour;
  • decide which concerns belong outside middleware.

Mental model: a controlled wrapper

Middleware receives a handler and returns a handler:

type Middleware func(http.Handler) http.Handler

It performs work before the next handler, after it, or both.

func Example(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Before
        next.ServeHTTP(w, r)
        // After
    })
}

Compose explicitly

func chain(handler http.Handler, middleware ...Middleware) http.Handler {
    for index := len(middleware) - 1; index >= 0; index-- {
        handler = middleware[index](handler)
    }
    return handler
}
handler := chain(
    routes,
    Recover(logger),
    RequestID,
    AccessLog(logger),
    Authenticate(authenticator),
)

The first item is outermost. Recovery should generally wrap code that might panic. Request ID generation should happen before logging needs the ID. Authentication may run only for protected route groups rather than every endpoint.

Request IDs

Use a private context-key type to avoid collisions:

type contextKey int

const requestIDKey contextKey = iota

func RequestID(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        requestID := newRequestID()
        ctx := context.WithValue(r.Context(), requestIDKey, requestID)
        w.Header().Set("X-Request-ID", requestID)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

Validate any incoming request ID before trusting or echoing it. Many services generate their own ID and record an upstream trace identifier separately.

Context values are suitable for small request-scoped metadata such as authenticated identity or tracing IDs. They are not a replacement for normal function parameters.

Record response status

type statusWriter struct {
    http.ResponseWriter
    status int
}

func (w *statusWriter) WriteHeader(status int) {
    if w.status != 0 {
        return
    }
    w.status = status
    w.ResponseWriter.WriteHeader(status)
}

func (w *statusWriter) Write(data []byte) (int, error) {
    if w.status == 0 {
        w.WriteHeader(http.StatusOK)
    }
    return w.ResponseWriter.Write(data)
}

Wrapping ResponseWriter can hide optional interfaces used by streaming, connection takeover, or optimised copying. On modern Go versions, http.ResponseController can access supported capabilities without requiring every wrapper to expose each optional interface manually. Test the behaviours your server needs.

Recover at the HTTP boundary

func Recover(logger *slog.Logger) Middleware {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            defer func() {
                if recovered := recover(); recovered != nil {
                    logger.ErrorContext(r.Context(), "handler panic", "panic", recovered)
                    http.Error(w, "Internal Server Error", http.StatusInternalServerError)
                }
            }()
            next.ServeHTTP(w, r)
        })
    }
}

Recovery keeps one handler panic from terminating the process, but the response may already be partially written. A panic still represents a defect that should be investigated. Do not use recovery instead of normal errors.

What should not be generic middleware?

Business validation, database transactions, and use-case-specific authorization often belong in the application flow because they need domain information. Forcing them into generic wrappers can hide important decisions.

Common mistakes

  • Unknown middleware order: logging misses request IDs or recovery misses an inner wrapper.
  • Writing a response and still calling next: two handlers compete to write headers and bodies.
  • Using string context keys: unrelated packages can collide.
  • Trusting forwarded headers from any client: only honour them behind configured trusted proxies.
  • Adding every concern globally: public health endpoints and authenticated business routes may need different chains.

Practice

Implement request ID, access logging, and recovery middleware. Compose them so a panic is logged with its request ID and becomes a safe 500 response. Test normal, explicit error, and panic handlers.

Summary

  • Middleware wraps handlers with shared transport-level behaviour.
  • Composition order changes observable behaviour and must be tested.
  • Context carries small request-scoped metadata, not arbitrary dependencies.
  • Response wrappers must preserve the capabilities an application uses.
  • Keep use-case-specific business decisions in application code.

Ready to wrap up?

Mark this complete when you can explain the main idea and finish the practice task.

Copyright © 2026