1
0
mirror of https://github.com/labstack/echo.git synced 2025-07-15 01:34:53 +02:00

Middleware as structs

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana
2016-02-17 21:01:47 -08:00
committed by Vishal Rana
parent e91717552f
commit c9a62e20b4
9 changed files with 187 additions and 120 deletions

View File

@ -8,21 +8,37 @@ import (
"github.com/labstack/echo"
)
type (
Recover struct {
priority int
}
)
func NewRecover() *Recover {
return &Recover{}
}
func (r *Recover) SetPriority(p int) {
r.priority = p
}
func (r *Recover) Priority() int {
return r.priority
}
// Recover returns a middleware which recovers from panics anywhere in the chain
// and handles the control to the centralized HTTPErrorHandler.
func Recover() echo.MiddlewareFunc {
return func(h echo.Handler) echo.Handler {
// TODO: Provide better stack trace `https://github.com/go-errors/errors` `https://github.com/docker/libcontainer/tree/master/stacktrace`
return echo.HandlerFunc(func(c echo.Context) error {
defer func() {
if err := recover(); err != nil {
trace := make([]byte, 1<<16)
n := runtime.Stack(trace, true)
c.Error(fmt.Errorf("panic recover\n %v\n stack trace %d bytes\n %s",
err, n, trace[:n]))
}
}()
return h.Handle(c)
})
}
func (*Recover) Handle(h echo.Handler) echo.Handler {
// TODO: Provide better stack trace `https://github.com/go-errors/errors` `https://github.com/docker/libcontainer/tree/master/stacktrace`
return echo.HandlerFunc(func(c echo.Context) error {
defer func() {
if err := recover(); err != nil {
trace := make([]byte, 1<<16)
n := runtime.Stack(trace, true)
c.Error(fmt.Errorf("panic recover\n %v\n stack trace %d bytes\n %s",
err, n, trace[:n]))
}
}()
return h.Handle(c)
})
}