Add context methods for the acme database

This commit is contained in:
Mariano Cano 2022-04-27 12:11:00 -07:00
parent 0446e82320
commit bd412c9f42

View file

@ -48,6 +48,29 @@ type DB interface {
UpdateOrder(ctx context.Context, o *Order) error
}
type dbKey struct{}
// NewContext adds the given acme database to the context.
func NewContext(ctx context.Context, db DB) context.Context {
return context.WithValue(ctx, dbKey{}, db)
}
// FromContext returns the current acme database from the given context.
func FromContext(ctx context.Context) (db DB, ok bool) {
db, ok = ctx.Value(dbKey{}).(DB)
return
}
// MustFromContext returns the current database from the given context. It
// will panic if it's not in the context.
func MustFromContext(ctx context.Context) DB {
if db, ok := FromContext(ctx); !ok {
panic("acme database is not in the context")
} else {
return db
}
}
// MockDB is an implementation of the DB interface that should only be used as
// a mock in tests.
type MockDB struct {