Go Academy · Lesson

HTTP Middleware Chain Fundamentals

Wrapping http.Handler and chaining with next

Lesson 1 of 413 steps

HTTP Middleware Chain Fundamentals is a free Go Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, and your progress syncs across the web and the CoddyKit app. The Go Academy course includes 4 lessons in total.

Middleware in net/http

In Go's standard library, middleware is a function that accepts an http.Handler and returns a new http.Handler with additional behaviour wrapped around the original.

type Middleware func(http.Handler) http.Handler

Basic middleware

The inner HandlerFunc wraps the original handler with pre/post logic:

func Logger(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Printf("→ %s %s", r.Method, r.URL.Path)
        next.ServeHTTP(w, r)
        log.Printf("← %s %s done", r.Method, r.URL.Path)
    })
}

Applying middleware

Wrap handlers before registering them with the mux:

mux := http.NewServeMux()
mux.Handle("/api/", Logger(Auth(apiHandler)))
http.ListenAndServe(":8080", mux)

Middleware chain helper

A chain function applies multiple middleware in a readable, left-to-right order:

func Chain(h http.Handler, ms ...func(http.Handler) http.Handler) http.Handler {
    for i := len(ms)-1; i >= 0; i-- { h = ms[i](h) }
    return h
}
// Usage: Chain(handler, Logger, Auth, RateLimit)

Context in middleware

Attach request-scoped values by creating a derived context and wrapping the request:

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

Response writer wrapper

Capture the status code written by a handler by wrapping the ResponseWriter:

type captureWriter struct {
    http.ResponseWriter
    status int
}
func (cw *captureWriter) WriteHeader(code int) {
    cw.status = code
    cw.ResponseWriter.WriteHeader(code)
}

Panic recovery middleware

Recover from panics to prevent the server from crashing:

func Recovery(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        defer func() {
            if rec := recover(); rec != nil {
                http.Error(w, "Internal Server Error", 500)
            }
        }()
        next.ServeHTTP(w, r)
    })
}

Order matters

Middleware runs in the order it wraps the handler. Recovery should be outermost (wraps everything). Auth before business logic. Logging usually outermost after Recovery.

Compatibility with third-party routers

Because middleware follows the standard func(http.Handler) http.Handler signature, it is compatible with chi, gorilla/mux, and any router that accepts http.Handler.

Global vs route-specific

Apply middleware globally to the entire mux, or wrap individual handlers for route-specific behaviour. chi's subrouters make group-level middleware cleaner.

Testing middleware

Use httptest.NewRecorder and httptest.NewRequest to test middleware in isolation without starting a real server.

w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", nil)
Logger(http.HandlerFunc(noop)).ServeHTTP(w, r)

Quick Check

What is the standard net/http middleware signature?

Recap: Middleware Chain

Key points:

  • func(http.Handler) http.Handler is the standard signature
  • Use a Chain helper to avoid deep nesting
  • r.WithContext(ctx) to attach values; capture writer to record status
  • Recovery outermost; Auth before business logic; Logging after Recovery
Free to start

Learn Go with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “HTTP Middleware Chain Fundamentals” lesson free?

Yes — any 3 lessons of the Go Academy learning path, including “HTTP Middleware Chain Fundamentals”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Go Academy course includes 4 lessons in total.

What will I learn in “HTTP Middleware Chain Fundamentals”?

Wrapping http.Handler and chaining with next You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

How long does the “HTTP Middleware Chain Fundamentals” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. HTTP Middleware Chain Fundamentals
  2. Logging and Request ID Middleware
  3. Auth and Rate Limiting Middleware
  4. CORS and Panic Recovery Middleware
← Back to Go Academy