Skip to content

Go HTTP Middleware Chain: Nesting Correctly

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about Go HTTP Middleware Chain: Nesting Correctly. We cover key concepts, practical examples, and best practices.

Middleware chains in Go -- Learn the correct way to compose HTTP middleware so logging, auth, and handler logic execute in the expected order.

The Problem

When chaining middleware in Go, the outermost middleware wraps the inner handler. The first middleware applied runs first on the request path but last on the response path. Confusing this order causes logging after responses or auth checks happening too late.

Wrong

http.Handle("/", loggingMiddleware(
    authMiddleware(
        http.HandlerFunc(finalHandler))))

Output:

$ curl http://localhost:8080/protected
// Response closed before logging sees it -- broken!
func chain(h http.Handler, m ...func(http.Handler) http.Handler) http.Handler {
    for i := len(m) - 1; i >= 0; i-- { h = m[i](h) }
    return h
}
http.Handle("/", chain(finalHandler, loggingMiddleware, authMiddleware))

Output:

$ curl http://localhost:8080/protected
// logging: REQUEST / auth: OK / handler: done / logging: RESPONSE (200, 42ms)

Prevention

  • Apply middleware in the order you want execution
  • Use a chain helper function to reverse middleware order
  • Use libraries like justinas/alice for readable chains
  • Panic recovery must be the outermost wrapper
  • Always call next.ServeHTTP(w, r) or the chain breaks

Common Mistakes with http middleware chain

  1. Using foldl instead of foldl' causing stack overflow on large lists
  2. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  3. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**What is the standard middleware signature?**

func(next http.Handler) http.Handler. It returns a new handler that wraps the next one.

Can I chain middleware with different signatures?

Use adapter functions to convert custom middleware to the standard func(http.Handler) http.Handler pattern.

Does middleware order matter for performance?

Yes. Put fast checks (auth tokens, rate limiting) early. Put logging outermost so it measures total time.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro