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 achieving flexibility on a single handler, or by using a structure.
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.
How to do it...
The following steps cover the writing and running of your application:
- From your Terminal or console application,createa new directory called~/projects/go-programming-cookbook/chapter8/controllers, and navigate to this directory.
- Run the following command:
$ go mod init github.com/PacktPublishing/Go-Programming-Cookbook-Second...