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 expensive 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 router (such as
http.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
- Build up a chain of handlers containing both our middleware handler and our normal application handler, which we can register with a router.
I'll explain how.
Hopefully you're already familiar with the following pattern for constructing a handler:
In this code we put our handler logic (a simple
w.Write()) in an anonymous function which closes-over
message variable to form a closure. We then convert the closure to a handler with the
http.HandlerFunc() adapter, and then return it.
We can use this same pattern to help us 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
http.ServeMuxrouter in Go's
- We can create an arbitrarily long handler chain by nesting middleware functions inside each other.
Illustrating the Flow of Control
Let's look at a stripped-down example with some middleware that writes some log messages in your terminal window:
If you run this application and make a request to
http://localhost:3000, you should see some log output similar to
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
In the example above I've included a conditional return in the
middlewareTwo function. Try it by
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
Understood. How About a Proper Example?
OK, let's say that we're building a service which processes requests containing a JSON body.
We want to create some middleware which a) checks for the existence of a
Content-Type header and b) if
the header exists, check that it has the mime type
application/json. 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 making some requests using cURL:
Using Third-Party Middleware
Rather than rolling your own middleware all the time you might decide to save time and effort and use an existing third-party package. Let's take a look at a couple of examples to help demonstrate some common patterns that you might come across.
The first third-party middleware we'll demonstrate is
goji/httpauth, which provides
HTTP Basic Authentication functionality.
When using this package you call a helper function in order to setup the chainable middleware. Specifically,
you call the
function, and this returns a middleware function with the signature
— which you can then use in exactly the same way as any custom-built middleware.
If you run this code then visit
http://localhost:3000 in your
browser you should get a username and password prompt like so:
Entering the wrong username and password should result in the prompt being redisplayed, clicking 'Cancel' should
result in a plain-text
"Unauthorized" response, and using the correct username (
pa$$word) should result in an
That was pretty straightforward and easy to integrate. Let's now look at a different example using the
middleware from the
gorilla/handlers package, which
records request logs using the Apache Common Log
Instead of using the standard middleware signature that we've seen so far throughout this post, this middleware has
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 of using it in which we write logs to a
server.log file in the current
In a trivial case like this our code is fairly clear. But what happens if we want to use this as part of a larger middleware chain? We could easily end up with a declaration looking something like this...
... And that's pretty confusing!
To help tidy this up it's possible to create a constructor function which wraps the
LoggingHandler() middleware and returns a standard
func(http.Handler) http.Handler function
that we can nest neatly with other middleware. Like so:
If you run this application and make a few requests, your
server.log file should look something like
If you're interested, here's a gist of the three middleware handlers from this post combined in one example.
The justinas/alice package is very lightweight tool which provides some syntactic sugar for chaining middleware handlers. At it's most basic, it lets you rewrite this:
To 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: