CodeGym /课程 /Go SELF /Middleware chaining 与应用顺序

Middleware chaining 与应用顺序

Go SELF
第 62 级, 课程 0
可用

1. Introduction

If you write a server in a brute-force way, cross-cutting requirements appear almost immediately: add a header to every response, log every request, check access, limit the rate, catch panics. And suddenly you discover that the same code is duplicated in every handler. At some point you change one rule—for example, the error format—and start looking for “another 17 places where this needs to be fixed”.

Middleware solves this problem in the same way that a good habit of washing your hands solves the problem of “why did I catch a cold again?”: it is not magic, but consistency.

The key idea is: the handler deals with business logic, while middleware deals with cross-cutting policy around that logic.

The net/http contract: http.Handler as the wrapping point

Before building chains, it is worth looking again at the contract around which we are going to build. In net/http, a handler is any type that has the method ServeHTTP(w, r). That is why it is so easy to write adapters and wrappers in Go: you simply return another http.Handler that calls the next one internally. It is the same “adapter pattern”, just without the pompous wording.

Let’s recall the minimal server skeleton, heavily simplified:

package main

import (
	"log"
	"net/http"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	log.Fatal(http.ListenAndServe(":8080", mux))
}

Almost everything interesting in the server architecture below revolves around what exactly we pass to ListenAndServe as the second argument.

Middleware as a wrapper function

When you first hear “middleware”, you want to ask: “Is this a library? Is this a framework? Is this a religion?” In reality it is just a function that takes one handler and returns another handler. In other words, literally a “wrapper” around http.Handler.

The most popular signature looks like this:

func(next http.Handler) http.Handler

To make the code easier to read, people usually introduce a named type:

package httpmw

import "net/http"

type Middleware func(http.Handler) http.Handler

After that, any middleware reads as “take the next layer (next) and return a new layer”.

2. Middleware mechanics: “before → next → after”

Almost any middleware internally looks like “do something before the request”, then pass control down, and then “do something after”. It is convenient to imagine this as an onion: the outer layer sees the request first, and the response last.

Let’s create a minimal middleware that adds a header to all responses. (Yes, it is simple, but it is ideal for understanding the mechanics.)

package httpmw

import "net/http"

func WithHeader(name, value string) Middleware {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set(name, value) // "before"
			next.ServeHTTP(w, r)        // "pass down"
		})
	}
}

Notice that we use http.HandlerFunc, because it is the “function as handler” adapter. That means we do not have to declare a separate type X struct{} just for ServeHTTP.

Short-circuit: middleware can stop a request

Beginners often have an inner feeling that next.ServeHTTP(...) must always be called, otherwise “how will it go further?” But the point of some middleware is precisely to not let the request continue: access checks, limits, maintenance mode.

Let’s make an example of a “server under maintenance”: if the flag is enabled, respond immediately.

package httpmw

import "net/http"

func MaintenanceMode(enabled bool) Middleware {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if enabled {
				w.WriteHeader(http.StatusServiceUnavailable)
				return // short-circuit: do not go further
			}
			next.ServeHTTP(w, r)
		})
	}
}

The key thing here is the moral: middleware has the right to finish a request on its own. This is not a “hack”, but a core tool for building policies.

4. Middleware chains and application order

When there is more than one middleware, we want to apply them all to one mux (or to one handler). And then an important question arises: in what order are they applied?

If we have:

  • A — middleware #1
  • B — middleware #2
  • C — middleware #3
  • H — final handler (for example, mux)

then the logical “onion” usually looks like this:

A(B(C(H)))

So A is the outermost layer: it sees the request first and “escorts” the response last.

For understanding the order, the following diagram is useful:

flowchart TD
    R[HTTP request] --> A[Middleware A]
    A --> B[Middleware B]
    B --> C[Middleware C]
    C --> H["Final handler (mux)"]
    H --> C
    C --> B
    B --> A
    A --> W[HTTP response]

The important point here is: “forward” we go A → B → C → H, while “backward” (when the handler has already finished) we go H → C → B → A. That is why middleware order affects things like status logging or panic interception: the outer layer “sees everything” that happened inside.

The Chain function: building a chain with a readable order

Now we want the order to be:

  • explicitly visible in the code,
  • always assembled in the same way (not “somewhere like this, somewhere like that”),
  • not require manually nesting A(B(C(H))), because that is painful even to look at.

Let’s make a helper called Chain. The key trick is: apply middleware in reverse order, so the first one in the list becomes the outermost.

package httpmw

import "net/http"

type Middleware func(http.Handler) http.Handler

func Chain(h http.Handler, mws ...Middleware) http.Handler {
	for i := len(mws) - 1; i >= 0; i-- {
		h = mws[i](h)
	}
	return h
}

And this is the “magic without magic”: the list is read left to right (as we are used to), but applied right to left, so the result is mws[0](mws[1](...h)).

Who runs first: a mini table

To avoid getting completely confused (and you will get confused, that is tradition), keep a simple table. Suppose:

h := Chain(mux, A, B, C)

Then:

Entity Who sees the request first Who calls next first Who “closes” the response last
A
yes yes yes
B
no after
A
before
A
C
no after
B
before
B
mux
no innermost innermost

If you feel a slight dizziness, that is normal. Middleware order first feels like “headphone wires”: it seems like you did nothing, but somehow everything got tangled anyway.

“Manual nesting” vs Chain

To learn how to read other people’s code, it is useful to see both variants. Sometimes you will encounter something like this:

h := A(B(C(mux)))

This is honest, simple, and works. But after a week A(B(C(D(E(F(...))))) looks like the Wi‑Fi password in a cafe: the symbols are there, but there is not much joy.

With Chain, the same thing becomes:

h := Chain(mux, A, B, C)

And now it reads as “A on the outside, then B, then C”. That is exactly what we want.

5. Plugging chaining into the application without rewriting the server

Until now, we have been passing our mux to ListenAndServe. Now we will pass a wrapped mux. And this is an important architectural win: we change the behavior of the entire server without touching the endpoints themselves.

A simplified but essentially correct main.go skeleton:

package main

import (
	"log"
	"net/http"
	"time"

	"example.com/taskapi/httpmw"
)

func main() {
	mux := http.NewServeMux()
	registerRoutes(mux)

	h := httpmw.Chain(mux,
		httpmw.WithHeader("Content-Type", "application/json; charset=utf-8"),
		httpmw.MaintenanceMode(false),
		httpmw.WithTimeoutHint(2*time.Second),
	)

	log.Fatal(http.ListenAndServe(":8080", h))
}

Here registerRoutes(mux) is your usual endpoint registration code (/api/v1/tasks, /api/v1/tasks/{id}, etc.), which we do not want to touch. And WithTimeoutHint is another simple middleware, which we will write now to see an example of a “parameterized” wrapper.

An example of middleware with a parameter: WithTimeoutHint

We want to show middleware that takes a parameter and does something useful, but does not require complicated topics. Headers are ideal for this.

Suppose we want to add a “hint” to the client: the server expects requests to be fast (this is not a real timeout, just a demonstration of “cross-cutting behavior”).

package httpmw

import (
	"net/http"
	"time"
)

func WithTimeoutHint(d time.Duration) Middleware {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("X-Timeout-Hint", d.String())
			next.ServeHTTP(w, r)
		})
	}
}

The advantage of this example is that it shows “middleware as a factory”: you set the parameter once when assembling the server, and then the same rule works for every request.

Why it is better to assemble the chain in one place

When the middleware chain is assembled in one place, usually in main, you get almost free benefits.

First, the order can be read with your eyes as the server’s contract: top to bottom lists the policies that apply to all requests. Second, if something breaks in the logic—for example, headers suddenly disappear or the server stops responding to part of the requests—you check one file instead of running around dozens of handlers.

And finally, it disciplines you: one middleware, one responsibility. When you start mixing headers, auth, logging, and panic handling inside one wrapper, you go back to that same “noodle”, only in a trendier sauce.

6. A nuance about Context: how middleware passes data downward

We will not go deep into storing data in context right now (that is a separate big topic), but it is important to note: middleware often does not only set headers, but also adds something to r.Context() and passes it further via r.WithContext(...).

Why is this even possible? Because http.Request already contains a Context, and the standard library expects you to respect the lifetime of the request through context (cancellation, deadlines, metadata).

For now, just remember this idea: if middleware “created a new context”, it must be put back into r, otherwise the lower layers will not see the changes.

7. Typical mistakes in chaining and middleware order

Mistake #1: wrong expectation about order (“why doesn’t logging see what I wanted?”).
A very common confusion: you put the middleware first in the list, but expect it to “run after everything”. In reality, the first item in the list is usually the outermost one: it sees the request first and finishes the response last. If you need to “run closer to the handler”, then the layer must be deeper (to the right in the list).

Mistake #2: forgetting to call next.ServeHTTP(w, r) where the request should be allowed to continue.
This is classic: you wrote middleware, checked one case, everything seems fine. Then it turns out that the server only responds with 401/403/something else—and the “normal” requests just do not pass through. The cure is discipline: keep the “before → next → after” skeleton in mind and explicitly check all return branches.

Mistake #3: accidentally calling next.ServeHTTP twice.
Sometimes beginners try to do a “repeat call” or mistakenly call next both inside an if and after the if. The result: the handler writes to ResponseWriter twice, strange responses appear, and sometimes there are panics. Almost always a middleware should call next exactly once (or zero times, if short-circuiting).

Mistake #4: writing headers too late.
Headers need to be set before anything below starts writing the response body or calls WriteHeader. If the inner handler has already written the body, then “changing the header later” is like trying to rewrite the end credits after the movie has already left the theaters: theoretically desirable, practically too late.

Mistake #5: assembling the chain “in different places” and letting the order drift.
First you wrap mux in one file, then some handler wraps another handler “locally”, then in tests a third scheme appears—and you lose track of what is a global policy and what is a local exception. A good rule is: the common middleware order is defined once at the application boundary, and local wrappers are used only if you understand very well why.

1
任务
Go SELF, 第 62 级, 课程 0
已锁定
响应头输出
响应头输出
1
任务
Go SELF, 第 62 级, 课程 0
已锁定
Yangcong shi lian
Yangcong shi lian
评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION