Using structs and closures for stateful handlers
Due to the sparse signatures of HTTP handler functions, it may seem tricky to add state to a handler. For example, there are a variety of ways to include a database connection. Two approaches to doing this are to pass in the state via closures, which is useful for flexibility on a single handler, or by using a struct.
This recipe will demonstrate both. We'll use a struct controller to store a storage interface and create two routes with a single handler that are modified by an outer function.
Getting ready
Refer to the steps given in the Getting ready section of the Working with web handlers, requests, and ResponseWriters recipe.
How to do it...
These steps cover writing and running your application:
- From your terminal/console application, create and navigate to the
chapter7/rest
directory.
- Copy tests from https://github.com/agtorre/go-cookbook/tree/master/chapter7/controllers or use this as an exercise to write some of your own.
- Create a file called...