Go Middleware Chaining

Guy J Grigsby
Star Gazers
Published in
2 min readFeb 9, 2021

A lot of the work I do in Go is around / on web services and website backends. This kind of work is not new and there are well tested patterns that work. One such pattern is that of the middleware. In this context, a middleware is a request handler that that handles every request before the route handler takes over. Some examples of types of middleware handleres that I have found useful are loggers, metrics, auth, and tracing. Basically anything that needs to handle every request prior to the route handler kicking in.

To clarify, let’s look at the following example. Let’s say we have a website that where users inventory/share trading cards. Each user has an account that is login/password protected. An Auth middleware is a good choice and we’ll include an access logging middleware too to keep track of who logged in.

No matter what the user wants to do, they go through the middleware in order. Kind of like a chain. Now for the fun part.

Let’s do it in Go!

Like a lot of Go patterns, including a common request handler pattern, middleware chaining is functional. We create a number of handlers and chain them together!

First we need the basics, a webserver:

Hopefully this looks familiar to most folks. We create a servemux and give it a handler. Any request to /login will be handled by this.

We’ll have to modify main in a second, but first we must define the auth middleware.

Yikes!

It looks like a lot. We have a closure within a closure. The innermost function is will handle our auth. The next function out is the required definition for our middleware chainer and the outermost function allows us to pass arbitrary values to the middleware. If we don’t need to pass anything else in, like for an access logger, we can skip the outmost func. For example:

Now we add our new functions to our main with the chainer, which we have yet to write.

And for the coup de grâce, the chainer.

We recursively line up our middlewares.

And there you have it! Middleware chaining in Go.

There is quite a bit more reading out there on Google. It may be that we are making thing more complicated than necessary, but all in all, I think it’s pretty elegant.

--

--

Guy J Grigsby
Star Gazers

Technologist, taco lover and Gopher. Technologist and software engineer in distributed systems. Neuro-divergent.