Middleware

Code that wraps every request

Some work belongs to every endpoint: logging each request, checking a login token, timing how long a handler ran. You don't want to copy that into all twenty handlers. Middleware is the answer β€” a function that wraps a handler, does its work, and passes control along.

In Go, a handler is anything satisfying the http.Handler interface (it has a ServeHTTP(w, r) method). Middleware is a function that takes a handler and returns a new handler:

func(next http.Handler) http.Handler

The next handler is the real work; the returned handler is your wrapper around it.