Creating custom middleware
Middleware functions are just functions that take in a next
function and return a function. We are able to do this in Go because functions are first-class citizens, and they can be used as variables. By using this idea, we are able to use regular functions as parameters to middleware functions.
In order to create custom middleware for use within the Echo framework, all we need to do is create a function that conforms to the echo.MiddlewareFunc
type, which is as follows:
type MiddlewareFunc func(HandlerFunc) HandlerFunc
The echo.MiddlewareFunc
type which defines what a middleware should be is simply a function which takes a next
parameter and returns a handler function. In the following example, we are creating a custom middleware which will assign a unique ID to every request that is made, and set our generated unique ID into the echo.Context
for use in later stages of the request pipeline. The following code is found in the $GOPATH/src/github.com/PacktPublishing...