Middleware for handlers in Go is an area that has been widely explored. There are a variety of packages for handling middleware. This recipe will create middleware from scratch and implement an ApplyMiddleware function to chain together a bunch of middlewares.
It will also explore setting values in the request context object and retrieving them later using middleware. This will all be done with a very basic handler to help demonstrate how to decouple middleware logic from your handlers.
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/middleware, and navigate to this directory.
- Run the following command:
$ go mod init github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter8/middleware...