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

  1. type CustomContext struct {
  2. echo.Context
  3. }
  4. func (c *CustomContext) Foo() {
  5. println("foo")
  6. }
  7. func (c *CustomContext) Bar() {
  8. println("bar")
  9. }

Create a middleware to extend default context

  1. e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
  2. return func(c echo.Context) error {
  3. cc := &CustomContext{c}
  4. return next(cc)
  5. }
  6. })

This middleware should be registered before any other middleware.

Use in handler

  1. e.GET("/", func(c echo.Context) error {
  2. cc := c.(*CustomContext)
  3. cc.Foo()
  4. cc.Bar()
  5. return cc.String(200, "OK")
  6. })