Extending Gorilla Mux Tutorial (Pt. 2)
This is Part 2. See Part 1
Repo Here — For those who would rather just see the code
Introduction
In part 1 we extended Gorilla Mux to provide AppContext
to handlers without having to use global variables. In this part we’ll go over managing many routes and adding basic Middlewares to the HandlerFunc
Problem 1
When you have oodles of Handlers (I only have 16, I’m sure bigger projects can have hundreds), it can get messy to have each of those Handlers declared individually in some kind of NewRouter
method.
Solution
We can get around this by declaring a Route
object which declares a route and then a NewRouter
method which handles building the router.
Sweet. Now when we want to add a new route, we can just do it in a single place. What about creating the router
object? Just iterate over the routes.
Problem 2
Whenever I write a new route, I (almost) always want it to be authorized. Adding logic to do authorization to every handler is cumbersome at best and unsafe at worst. If you make a change to your site’s authorization flow, and miss one of the handlers, the routes that handler is responsible for are potentially compromised.
Solution — Middlewares!
We can add a method which takes a http.Handler
and returns a function which implements the http.Handler
interface. We can define these
We can update the NewRouter
function very simply now as well. NOTE: The middlewares are executed on the way down. This means that CheckAuth
is called first, then SetContentTypeText.
Conclusion
That’s about it. Feel free to hit me with any questions and I’ll try to answer as best as I can. Thanks for reading!
Code Again:
https://github.com/nitronick600/gorilla-router-tutorial