goweb/middleware/debug/debug.go
William Petit 38f4c7b735 Move Debug and ServiceContainer middlewares into their own packages
- Implements From/Must accessors to facilitate context values retrieval
2018-12-07 10:13:53 +01:00

43 lines
961 B
Go

package debug
import (
"context"
"errors"
goweb "forge.cadoles.com/wpetit/goweb/middleware"
"github.com/go-chi/chi/middleware"
)
const (
// KeyDebug is the context key associated with the debug value
KeyDebug goweb.ContextKey = "debug"
)
// 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) {
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
}
// Debug expose the given debug flag as a context value
// on the HTTP requests
func Debug(debug bool) goweb.Middleware {
return middleware.WithValue(KeyDebug, debug)
}