Custom middleware

Echo comes with a very rich set of contributed middleware functions that perform a wide variety of different tasks. Since we decided to use JWT tokens for our authentication mechanism defined in the prior section, we can take advantage of the JWT middleware that ships with Echo to force only valid, authenticated users the ability to call particular resources. The following shows a general middleware that sets the signingKey for our JWT on the context, so that our login handler has access to it. It also shows how we can use grouping to limit middleware functions to specific subsets of resources from within $GOPATH/src/github.com/PacktPublishing/Echo-Essentials/chapter2/cmd/service/main.go:

        // Signing Key for our auth middleware
        var signingKey = []byte("superdupersecret!")
        e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
                return func(c echo.Context) error {
                        c.Set(models.SigningContextKey, signingKey)
                        return next(c)
                }
        })

        reminderGroup := e.Group("/reminder")
        reminderGroup.Use(middleware.JWT(signingKey))
        reminderGroup.POST("", handlers.CreateReminder)

Middleware functions are a great way to enrich requests with common functionality that can be reused across application handler code. The use of middleware will significantly simplify your code and allow for greater reuse across your application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.89.2