Extending Gorilla Mux Tutorial (Pt. 1)
I am a Golang hobbyist. Well, semi-hobbyist. I have an application which 2(!!) people pay me $100/month for, so technically, I’m a professional. Which is terrifying.
Everyone wants the code first, so here it is: CODEZ. It’s broken down into parts by branch.
If you’re coming back, take a look at Part 2
Introduction
In this tutorial, I’ll show how I extended Gorilla to provide application context to all of my handlers without global variables. There’s also a few nuggets about how to write custom middlewares and as well as my method for defining routes declaratively.
Background
(This tutorial is based on Gorilla, but the concept can be applied to any routing library)
In the early stages of development, I would just declare any resources shared between handlers as global variables. Things like Postgres or Redis connection that I didn’t want to instantiate over and over again.
Problem
When your project starts to get big enough, it’s nice to be able to break things up logically, but then you have to have more clearly-defined interfaces between your packages. We can no longer depend on the global variable model.
Solution
We can provide a ContextedHandler
struct which defines an interface for our Handlers to extend which provides a function with an AppContext
struct
So now we have this great interface which will provide all of our handlers with a flexible context variable. Here’s an example of how you would implement it.
Now, HelloWorldHandler
can be moved to another package and imported. This helps keep your code modular. You could potentially package up just your routers and re-use them in a completely different project.
Up Next In Part 2
We’ll go over how we can elegantly handle a large number of Handlers as well as how to write very simple Middlewares for adding authentication and HTTP caching.