goweb/middleware/debug/debug.go

43 lines
954 B
Go
Raw Normal View History

package debug
2018-12-06 15:18:05 +01:00
import (
"context"
"errors"
"github.com/go-chi/chi/middleware"
2019-07-28 13:11:23 +02:00
goweb "gitlab.com/wpetit/goweb/middleware"
2018-12-06 15:18:05 +01:00
)
const (
// KeyDebug is the context key associated with the debug value
KeyDebug goweb.ContextKey = "debug"
2018-12-06 15:18:05 +01:00
)
// ErrInvalidDebug is returned when no debug value
// could be found on the given context
var ErrInvalidDebug = errors.New("invalid debug")
// From retrieves the debug value from the given context
func From(ctx context.Context) (bool, error) {
2018-12-06 15:18:05 +01:00
debug, ok := ctx.Value(KeyDebug).(bool)
if !ok {
return false, ErrInvalidDebug
}
return debug, nil
}
// Must retrieves the debug value from the given context or panics otherwise
func Must(ctx context.Context) bool {
debug, err := From(ctx)
if err != nil {
panic(err)
}
return debug
}
2018-12-06 15:18:05 +01:00
// Debug expose the given debug flag as a context value
// on the HTTP requests
func Debug(debug bool) goweb.Middleware {
2018-12-06 15:18:05 +01:00
return middleware.WithValue(KeyDebug, debug)
}