Context
echo.Context
represents the context of the current HTTP request. It holds request andresponse reference, path, path parameters, data, registered handler and APIs to readrequest and write response. As Context is an interface, it is easy to extend it withcustom APIs.
Extending Context
Define a custom context
type CustomContext struct {
echo.Context
}
func (c *CustomContext) Foo() {
println("foo")
}
func (c *CustomContext) Bar() {
println("bar")
}
Create a middleware to extend default context
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
cc := &CustomContext{c}
return next(cc)
}
})
This middleware should be registered before any other middleware.
Use in handler
e.GET("/", func(c echo.Context) error {
cc := c.(*CustomContext)
cc.Foo()
cc.Bar()
return cc.String(200, "OK")
})