registry.go

 1package cache
 2
 3import (
 4	"context"
 5	"fmt"
 6	"sync"
 7)
 8
 9// Constructor is a function that returns a new cache.
10type Constructor func(context.Context, ...Option) (Cache, error)
11
12var (
13	registry = map[string]Constructor{}
14	mtx      sync.RWMutex
15
16	// ErrCacheNotFound is returned when a cache is not found.
17	ErrCacheNotFound = fmt.Errorf("cache not found")
18)
19
20// Register registers a cache.
21func Register(name string, fn Constructor) {
22	mtx.Lock()
23	defer mtx.Unlock()
24
25	registry[name] = fn
26}
27
28// New returns a new cache.
29func New(name string, ctx context.Context, opts ...Option) (Cache, error) {
30	mtx.RLock()
31	fn, ok := registry[name]
32	mtx.RUnlock()
33
34	if !ok {
35		return nil, ErrCacheNotFound
36	}
37
38	return fn(ctx, opts...)
39}