5
0
mirror of https://github.com/cwinfo/matterbridge.git synced 2024-11-25 12:11:35 +00:00
matterbridge/vendor/github.com/labstack/echo/middleware/recover.go

82 lines
2.0 KiB
Go
Raw Normal View History

2017-02-18 22:00:46 +00:00
package middleware
import (
"fmt"
"runtime"
"github.com/labstack/echo"
)
type (
// RecoverConfig defines the config for Recover middleware.
RecoverConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// Size of the stack to be printed.
// Optional. Default value 4KB.
2018-02-20 23:48:10 +00:00
StackSize int `yaml:"stack_size"`
2017-02-18 22:00:46 +00:00
// DisableStackAll disables formatting stack traces of all other goroutines
// into buffer after the trace for the current goroutine.
// Optional. Default value false.
2018-02-20 23:48:10 +00:00
DisableStackAll bool `yaml:"disable_stack_all"`
2017-02-18 22:00:46 +00:00
// DisablePrintStack disables printing stack trace.
// Optional. Default value as false.
2018-02-20 23:48:10 +00:00
DisablePrintStack bool `yaml:"disable_print_stack"`
2017-02-18 22:00:46 +00:00
}
)
var (
// DefaultRecoverConfig is the default Recover middleware config.
DefaultRecoverConfig = RecoverConfig{
Skipper: DefaultSkipper,
StackSize: 4 << 10, // 4 KB
DisableStackAll: false,
DisablePrintStack: false,
}
)
// 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 RecoverWithConfig(DefaultRecoverConfig)
}
// RecoverWithConfig returns a Recover middleware with config.
// See: `Recover()`.
func RecoverWithConfig(config RecoverConfig) echo.MiddlewareFunc {
// Defaults
if config.Skipper == nil {
config.Skipper = DefaultRecoverConfig.Skipper
}
if config.StackSize == 0 {
config.StackSize = DefaultRecoverConfig.StackSize
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if config.Skipper(c) {
return next(c)
}
defer func() {
if r := recover(); r != nil {
2017-12-07 22:00:56 +00:00
err, ok := r.(error)
if !ok {
2017-02-18 22:00:46 +00:00
err = fmt.Errorf("%v", r)
}
stack := make([]byte, config.StackSize)
length := runtime.Stack(stack, !config.DisableStackAll)
if !config.DisablePrintStack {
2017-12-07 22:00:56 +00:00
c.Logger().Printf("[PANIC RECOVER] %v %s\n", err, stack[:length])
2017-02-18 22:00:46 +00:00
}
c.Error(err)
}
}()
return next(c)
}
}
}