Go Middleware Explained with Examples

Updated 4 min read
Go Middleware featured image: cards for logging, panic recovery and API key checks

Go middleware wraps your HTTP handlers with shared behaviour such as logging, panic recovery and authentication. In this post, you will write each of these as a small function. Then you will chain them together cleanly, so every route gets them for free.

You saw a tiny logging example in the Go HTTP server tutorial. Now we go further. Middleware is built from closures, so a quick look at Go closures and anonymous functions will help too.

What Is Go Middleware?

In short, middleware is a function that takes a handler and returns a new handler. The new handler does some work, calls the original one and may do more work afterwards.

func(next http.Handler) http.Handler

Think of airport security. Before you reach the plane, you pass check-in, a bag scan and a passport desk. Each step can stop you or let you through. Similarly, each layer of Go middleware can reject a request or pass it on to the next one.

Logging Middleware with Status Codes

type statusRecorder struct {
	http.ResponseWriter
	status int
}

func (s *statusRecorder) WriteHeader(code int) {
	s.status = code
	s.ResponseWriter.WriteHeader(code)
}

func Logging(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
		next.ServeHTTP(rec, r)
		log.Printf("%s %s %d %v", r.Method, r.URL.Path, rec.status, time.Since(start).Round(time.Millisecond))
	})
}

The standard ResponseWriter never tells you which status was sent. So we wrap it in our own type that remembers the code. This trick uses Go struct embedding, because every other method is promoted from the embedded writer.

Recovery Middleware

func Recover(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if err := recover(); err != nil {
				log.Printf("panic: %v", err)
				http.Error(w, "internal server error", http.StatusInternalServerError)
			}
		}()
		next.ServeHTTP(w, r)
	})
}

A panic in one handler should never break the whole app. Therefore, this layer catches it with recover and sends a clean 500 response instead. You learned this pattern in Go panic and recover.

Go Middleware That Takes Settings

func RequireAPIKey(key string) Middleware {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.Header.Get("X-API-Key") != key {
				http.Error(w, "unauthorized", http.StatusUnauthorized)
				return
			}
			next.ServeHTTP(w, r)
		})
	}
}

Sometimes a layer needs configuration, such as a secret key. In that case, write a function that returns the middleware. Notice the early return. Since it never calls next, the handler behind it is fully protected.

Chaining Go Middleware

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
}

app := Chain(mux, Logging, Recover, RequireAPIKey("secret123"))
log.Fatal(http.ListenAndServe(":8080", app))

Without a helper, you would write Logging(Recover(RequireAPIKey("secret123")(mux))), which is hard to read. Instead, Chain applies the list from the last layer to the first. As a result, the request passes through them in the order you wrote them. The diagram below shows that journey.

Go Middleware diagram showing Logging, Recover and RequireAPIKey layers wrapped around a handler

A request passes through Logging, Recover and the API key check on the way in, and the response travels back out through the same layers.

Seeing It Work

/orders key=secret123 -> 200 order list
  log: GET /orders 200 0s
/orders key=wrong     -> 401 unauthorized
  log: GET /orders 401 0s
/boom   key=secret123 -> 500 internal server error
  log: panic: something broke
  log: GET /boom 500 0s

We tested each case of this Go middleware chain with httptest. Logging saw every request, including the rejected one and the panic. In other words, the order of the chain matters. Logging sits on the outside, so it records the final status of everything inside it.

Common Mistakes with Go Middleware

Problem you seeWhy it happensHow to fix it
Protected route runs without a keyBecause the check forgot to return.So return right after http.Error.
Logs always show status 200Because the plain ResponseWriter hides the code.So wrap it in a status recorder.
Panicked requests are missing from the access logBecause Recover sits outside Logging, so the panic skips the log line.So put Logging first in the chain.
Middleware runs twiceBecause the same layer was added in two places.So apply shared layers once, at the top.

Middleware design is a common backend interview topic. So practise with my Go interview questions and answers.

Official Resources

These pages come straight from the Go team, so they stay accurate and up to date.

Quick Recap

  • Go middleware takes a handler and returns a new handler.
  • Logging, recovery and authentication are the most common layers.
  • Wrap the ResponseWriter to capture the status code.
  • A function that returns middleware lets you pass settings.
  • A Chain helper keeps the order clear and readable.

What’s Next?

Your server now has solid layers around every route. Next, we will flip sides and call other APIs with the Go HTTP client.

Next lesson: Go HTTP Client Explained for Beginners