Controllers
In this example we will experiment with building our own controller
implementation using some standard features in Go. But first, lets start with
the problems we are trying to solve. Say we are using the library that
we talked about in previous chapters:
1. Use a global variable: This isn’t too bad for small programs, but when
the program gets larger it quickly becomes a maintenance nightmare.
When your program grows in size, you will start to notice that many of your
s will share the same dependencies and you will have a lot of
these closurized http.Handlers
with the same arguments. The way I like to
clean this up is to write a little base controller implementation that affords
me a few wins:
- Allows me to share the dependencies across
http.Handler
s that have similar goals or concepts. - Avoids global variables and functions for easy testing/mocking.
Thats it! That is all the implementation that we need to have the power of
controllers at our fingertips. All we have left to do is implement an example
controller:
- Extend to have multiple actions for different routes in your application.
- Play with more controller implementations, get creative.