Move Debug and ServiceContainer middlewares into their own packages
- Implements From/Must accessors to facilitate context values retrieval
This commit is contained in:
42
middleware/debug/debug.go
Normal file
42
middleware/debug/debug.go
Normal file
@ -0,0 +1,42 @@
|
||||
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)
|
||||
}
|
22
middleware/debug/debug_test.go
Normal file
22
middleware/debug/debug_test.go
Normal file
@ -0,0 +1,22 @@
|
||||
package debug
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestContextDebug(t *testing.T) {
|
||||
|
||||
debug := false
|
||||
ctx := context.WithValue(context.Background(), KeyDebug, debug)
|
||||
|
||||
dbg, err := From(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if dbg {
|
||||
t.Fatal("debug should be false")
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user