/
cache.go
79 lines (56 loc) · 1.22 KB
/
cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package cache
import (
"context"
"github.com/aaronland/go-roster"
"io"
_ "log"
"net/url"
)
type Cache interface {
Close(context.Context) error
Name() string
Get(context.Context, string) (io.ReadSeekCloser, error)
Set(context.Context, string, io.ReadSeekCloser) (io.ReadSeekCloser, error)
Unset(context.Context, string) error
Hits() int64
Misses() int64
Evictions() int64
Size() int64
SizeWithContext(context.Context) int64
}
type CacheInitializationFunc func(ctx context.Context, uri string) (Cache, error)
var caches roster.Roster
func ensureRoster() error {
if caches == nil {
r, err := roster.NewDefaultRoster()
if err != nil {
return err
}
caches = r
}
return nil
}
func RegisterCache(ctx context.Context, name string, c CacheInitializationFunc) error {
err := ensureRoster()
if err != nil {
return err
}
return caches.Register(ctx, name, c)
}
func NewCache(ctx context.Context, uri string) (Cache, error) {
u, err := url.Parse(uri)
if err != nil {
return nil, err
}
scheme := u.Scheme
i, err := caches.Driver(ctx, scheme)
if err != nil {
return nil, err
}
init := i.(CacheInitializationFunc)
c, err := init(ctx, uri)
if err != nil {
return nil, err
}
return c, nil
}