2018-12-07 10:13:53 +01:00
|
|
|
package debug
|
2018-12-06 15:18:05 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
|
2023-11-19 20:52:38 +01:00
|
|
|
"github.com/go-chi/chi/v5/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
|
2018-12-07 10:13:53 +01:00
|
|
|
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")
|
|
|
|
|
2018-12-07 10:13:53 +01:00
|
|
|
// 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
|
|
|
|
}
|
|
|
|
|
2018-12-07 10:13:53 +01:00
|
|
|
// 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
|
2018-12-07 10:13:53 +01:00
|
|
|
func Debug(debug bool) goweb.Middleware {
|
2018-12-06 15:18:05 +01:00
|
|
|
return middleware.WithValue(KeyDebug, debug)
|
|
|
|
}
|