Move Debug and ServiceContainer middlewares into their own packages

- Implements From/Must accessors to facilitate context values retrieval
This commit is contained in:
2018-12-07 10:13:53 +01:00
parent a2b0ab6471
commit 38f4c7b735
5 changed files with 40 additions and 23 deletions

42
middleware/debug/debug.go Normal file
View 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)
}

View 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")
}
}