Unit Testing Golang HTTP Middleware

Unit-Testing Golang HTTP Middleware is simple, but a topic that is not well covered. This post covers an example http middleware including unit tests.

Constructing and using idiomatic http middleware is a story that’s already been told. See this, this, or simply google it to learn more about the topic. Something you won’t find in that search is how to unit test http middleware in Golang.


Let’s Begin!

The example presented here is simple. It’s a basic ping server with simple authentication middleware. The authentication middleware will require user and password query params and validate those inputs against hard-coded values. The authentication flow (which we’ll be unit testing) follows.

$ curl “localhost:8080/ping”
MISSING_ARG_USER
$ curl “localhost:8080/ping?user=baduser”
NOT_AUTHORIZED
$ curl “localhost:8080/ping?user=test”
MISSING_ARG_PASSWORD
$ curl “localhost:8080/ping?user=test&password=badpassword”
NOT_AUTHORIZED
$ curl “localhost:8080/ping?user=test&password=abc123”
OK

The code that provides the above example follows.


Let’s Test!

In order to unit test the Auth middleware we’ll first need to construct a test http handler to pass to the Auth function.

With this test handler in place we can construct the following set of tests. Note that the tests also use the testify/assert package for simple assertions.


Wrapping Up

I hope this example has expanded on the current set of examples on constructing and using idiomatic http middleware in Golang.


Want to work on cool projects and have time to explore topics like this one? Come work with me and the rest of the awesome engineering team at bitly.is/hiring.