Context

echo.Context represents the context of the current HTTP request. It holds request and
response reference, path, path parameters, data, registered handler and APIs to read
request and write response. As Context is an interface, it is easy to extend it with
custom 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(h echo.HandlerFunc) echo.HandlerFunc {
  2. return func(c echo.Context) error {
  3. cc := &CustomContext{c}
  4. return h(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. })