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) *DB {
9 if db, ok := ctx.Value(contextKey).(*DB); ok {
10 return db
11 }
12 return nil
13}
14
15// WithContext returns a new context with the database.
16func WithContext(ctx context.Context, db *DB) context.Context {
17 return context.WithValue(ctx, contextKey, db)
18}