Middleware
Middleware is a function that takes a handler and returns a handler. It runs its own code, calls the next one, and may run more code after it returns, which is enough for logging, authentication, headers, recovery and timeouts. No framework is involved: the type is http.Handler, and a chain is a composition of functions.
A handler that wraps a handler
The wrapper prints before and after the mux. The order in the output is the whole idea: the before line, the handler's work, the after line. The response body is printed by the caller after the wrapper returns, which is why it comes last.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
func logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("before", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
fmt.Println("after", r.Method, r.URL.Path)
})
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /hello", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello")
})
h := logging(mux)
req := httptest.NewRequest("GET", "/hello", nil)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
fmt.Print("body: ", rec.Body.String())
}
go build -o main.go && ./main
before GET /hello
after GET /hello
body: hello
http.HandlerFunc turns a function into a handler, which is what lets the wrapper return one without a struct. A middleware that changes the request or the writer passes the changed value to next; the original is unchanged for the other wrappers.
The order of a chain
logging(withHeader(mux)) runs logging first, then the header wrapper, then the mux, and unwinds in reverse. A header set by the inner wrapper is present in the response the outer one sees, because both write into the same ResponseWriter. The order of the chain is the order of the calls in the main function, and reading it inside out is the usual mistake.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
func withHeader(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Served-By", "lesson")
next.ServeHTTP(w, r)
})
}
func logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("logging: before")
next.ServeHTTP(w, r)
fmt.Println("logging: after")
})
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /hello", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello")
})
h := logging(withHeader(mux))
req := httptest.NewRequest("GET", "/hello", nil)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
fmt.Println("header:", rec.Header().Get("X-Served-By"))
fmt.Print("body: ", rec.Body.String())
}
go build -o app main.go && ./app
logging: before
logging: after
header: lesson
body: hello
The header arrived even though the logging wrapper never set it, because the inner wrapper wrote it to the same recorder. A chain of ten wrappers is ten nested calls, which is why an order that puts the cheap checks (recovery, request id) outside the expensive ones (authentication, rate limit) is worth writing down.
Reading the status a handler wrote
A middleware that logs the status needs to see the number the handler passed to WriteHeader, and the interface does not offer a getter. The usual answer is a small wrapper around ResponseWriter that records the code and forwards it; the default is 200 because a handler that only writes a body never calls WriteHeader.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
type statusWriter struct {
http.ResponseWriter
status int
}
func (s *statusWriter) WriteHeader(code int) {
s.status = code
s.ResponseWriter.WriteHeader(code)
}
func logStatus(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(sw, r)
fmt.Println("status:", sw.status)
})
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("POST /notes", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusCreated)
fmt.Fprintln(w, "created")
})
h := logStatus(mux)
req := httptest.NewRequest("POST", "/notes", nil)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
fmt.Print("body: ", rec.Body.String())
}
go build -o app main.go && ./app
status: 201
body: created
The wrapper embeds the original writer, so every other method and the Header map pass through, and only WriteHeader is intercepted. A handler that writes a body without a status never calls the method, so the recorded default of 200 is what the server would have sent.
A recover middleware
A panic in a handler kills the process unless something recovers it. The middleware below recovers, logs the value and answers 500, so one broken request does not take the server down. It must be the outermost wrapper, or a panic in an inner middleware passes it by.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
func recoverer(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if v := recover(); v != nil {
fmt.Println("recovered:", v)
http.Error(w, "internal error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /panic", func(w http.ResponseWriter, r *http.Request) {
panic("boom")
})
h := recoverer(mux)
req := httptest.NewRequest("GET", "/panic", nil)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
fmt.Println("status:", rec.Code)
fmt.Print("body: ", rec.Body.String())
}
go build -o app main.go && ./app
recovered: boom
status: 500
body: internal error
The reply is a plain 500 with a short body, which is the right thing to show a client: the stack belongs in the log, not in the response. The standard library's server already recovers a panic and closes the connection, but it does not log a useful line or answer 500, which is why a service adds this wrapper.
Middleware is a function
A middleware has no interface to implement and no registration to call: it is the type func(http.Handler) http.Handler and a chain is a loop or a nested call. That smallness has two consequences. A wrapper that writes a header must do it before calling next, because the status goes out with the first write. And a wrapper that returns early, as an auth check does, must not call next, which is the whole mechanism of a rejection.
The request id wrapper builds the value the logging wrapper prints and the handler reads from the context, which is the context.WithValue rule from Part 6: request-scoped data crosses the boundary by context, and the id is the example that justifies it.
Exercises
- Swap the two wrappers in the chain and read the output. Which line moves, and what does the header show?
- Add a middleware that returns 401 and does not call next. What does the handler print, and what does the client see?
- Put the recover wrapper inside the logging one and panic in the handler. Which wrapper logs, and what happens to the process?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a middleware?
Answer
A function from http.Handler to http.Handler
It wraps a handler and returns one.
-
Where does the code before next.ServeHTTP run?
Answer
Before the wrapped handler
The after part runs when it returns.
-
What does the order of a chain follow?
Answer
The order of the calls that build it, outside in
The outermost wrapper runs first.
-
Why wrap ResponseWriter to read the status?
Answer
The interface has no getter for it
WriteHeader is intercepted and recorded.
-
What is the default status of a handler that only writes a body?
Answer
200
The first write sends it.
-
What does a recover middleware protect?
Answer
The process, by turning a panic into a 500
A panic in a handler otherwise ends the program.
-
Where must the recover wrapper be?
Answer
Outermost, so it sees every inner panic
A panic unwinds through the wrappers outside it.
-
When must a wrapper set a header?
Answer
Before calling next
The status goes out with the first write.
-
What does an auth middleware do to reject a request?
Answer
Writes the status and does not call next
Not calling next is the rejection.
-
How does a request id reach the handler?
Answer
Through the request context
It is request-scoped data.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev