Quellcode durchsuchen

Add context methods for the acme database

Mariano Cano vor 4 Jahren
Ursprung
Commit
bd412c9f42
1 geänderte Dateien mit 23 neuen und 0 gelöschten Zeilen
  1. 23 0
      acme/db.go

+ 23 - 0
acme/db.go

@@ -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 {