Making and Using HTTP Middleware
When you're building a web application there's probably some shared functionality that you want to run for many (or even all) HTTP requests. You might want to log every request, gzip every response, or check a cache before doing some heavy processing.
One way of organising this shared functionality is to set it up as middleware – self-contained code which independently acts on a request before or after your normal application handlers. In Go a common place to use middleware is between a ServeMux and your application handlers, so that the flow of control for a HTTP request looks like:
In this post I'm going to explain how to make custom middleware that works in this pattern, as well as running through some concrete examples of using third-party middleware packages.
The Basic Principles
Making and using middleware in Go is fundamentally simple. We want to:
- Implement our middleware so that it satisfies the http.Handler interface.
- Build up a chain of handlers containing both our middleware handler and our normal application handler, which we can register with a http.ServeMux.
I'll explain how.
Hopefully you're already familiar with the following method for constructing a handler (if not, it's probably best to read this primer before continuing).
In this handler we're placing our logic (a simple
w.Write) in an anonymous function and closing-over the
message variable to form a closure. We're then converting this closure to a handler by using the http.HandlerFunc adapter and returning it.
We can use this same approach to create a chain of handlers. Instead of passing a string into the closure (like above) we could pass the next handler in the chain as a variable, and then transfer control to this next handler by calling it's
This gives us a complete pattern for constructing middleware:
You'll notice that this middleware function has a
func(http.Handler) http.Handler signature. It accepts a handler as a parameter and returns a handler. This is useful for two reasons:
- Because it returns a handler we can register the middleware function directly with the standard ServeMux provided by the net/http package.
- We can create an arbitrarily long handler chain by nesting middleware functions inside each other. For example:
Illustrating the Flow of Control
Let's look at a stripped-down example with some middleware that simply writes log messages to stdout:
Run this application and make a request to http://localhost:3000. You should get log output similar to this:
It's clear to see how control is being passed through the handler chain in the order we nested them, and then back up again in the reverse direction.
We can stop control propagating through the chain at any point by issuing a
return from a middleware handler.
In the example above I've included a conditional return in the
middlewareTwo function. Try it by visiting http://localhost:3000/foo and checking the log again – you'll see that this time the request gets no further than
middlewareTwo before passing back up the chain.
Understood. How About a Proper Example?
OK, let's say that we're building a service which processes requests containing a XML body. We want to create some middleware which a) checks for the existence of a request body, and b) sniffs the body to make sure it is XML. If either of those checks fail, we want our middleware to write an error message and to stop the request from reaching our application handlers.
This looks good. Let's test it by creating a simple XML file:
And making some requests using cURL:
Using Third-Party Middleware
Rather than rolling your own middleware all the time you might want to use a third-party package. We're going to look at a couple here: goji/httpauth and Gorilla's LoggingHandler.
The goji/httpauth package provides HTTP Basic Authentication functionality. It has a SimpleBasicAuth helper which returns a function with the signature
func(http.Handler) http.Handler. This means we can use it in exactly the same way as our custom-built middleware.
If you run this example you should get the responses you'd expect for valid and invalid credentials:
Gorilla's LoggingHandler – which records Apache-style logs – is a bit different.
It uses the signature
func(out io.Writer, h http.Handler) http.Handler, so it takes not only the next handler but also the io.Writer that the log will be written to.
Here's a simple example in which we write logs to a
In a trivial case like this our code is fairly clear. But what happens if we want to use LoggingHandler as part of a larger middleware chain? We could easily end up with a declaration looking something like this...
... And that makes my brain hurt!
One way to make it clear is by creating a constructor function (let's call it
myLoggingHandler) with the signature
func(http.Handler) http.Handler. This will allow us to nest it more neatly with other middleware:
If you run this application and make a few requests your
server.log file should look something like this:
If you're interested, here's a gist of the three middleware handlers from this post combined in one example.
As a side note: notice that the Gorilla LoggingHandler is recording the response status (
200) and response length (
2) in the logs. This is interesting. How did the upstream logging middleware get to know about the response body written by our application handler?
It does this by defining it's own
responseLogger type which wraps
http.ResponseWriter, and creating custom
responseLogger.WriteHeader() methods. These methods not only write the response but also store the size and status for later examination. Gorilla's LoggingHandler passes
responseLogger onto the next handler in the chain, instead of the normal
Alice by Justinas Stankevičius is a clever and very lightweight package which provides some syntactic sugar for chaining middleware handlers. At it's most basic Alice lets you rewrite this:
In my eyes at least, that code is slightly clearer to understand at a glance. However, the real benefit of Alice is that it lets you to specify a handler chain once and reuse it for multiple routes. Like so: