context.go

 1package cache
 2
 3import "context"
 4
 5var contextKey = &struct{ string }{"cache"}
 6
 7// WithContext returns a new context with the cache.
 8func WithContext(ctx context.Context, c Cache) context.Context {
 9	if c == nil {
10		return ctx
11	}
12	return context.WithValue(ctx, contextKey, c)
13}
14
15// FromContext returns the cache from the context.
16// If no cache is found, nil is returned.
17func FromContext(ctx context.Context) Cache {
18	c, ok := ctx.Value(contextKey).(Cache)
19	if !ok {
20		return nil
21	}
22
23	return c
24}