Implementing and using middleware
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 middleware.
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.
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/middleware
directory. - Copy tests from https://github.com/agtorre/go-cookbook/tree/master/chapter7/middleware or use this as an exercise to write some of your own.
- Create a file called
middleware.go...