context.go

 1package db
 2
 3import "context"
 4
 5var contextKey = &struct{ string }{"db"}
 6
 7// FromContext returns the database from the context.
 8func FromContext(ctx context.Context) Database {
 9	if db, ok := ctx.Value(contextKey).(Database); ok {
10		return db
11	}
12	return nil
13}
14
15// WithContext returns a new context with the database attached.
16func WithContext(ctx context.Context, db Database) context.Context {
17	return context.WithValue(ctx, contextKey, db)
18}