/
cache.go
65 lines (57 loc) · 1.29 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
package pizza
import (
"errors"
"time"
)
type CacheValue[V any] struct {
val V
createdAt time.Time
}
type Cache[T any] struct {
ttl time.Duration
store map[string]CacheValue[T]
refresh func(key string) (T, error)
}
func NewCache[T any](ttl time.Duration, refreshFunc func(key string) (T, error)) Cache[T] {
return Cache[T]{
ttl: ttl,
store: make(map[string]CacheValue[T]),
refresh: refreshFunc,
}
}
func NewCache2[T any](ttl time.Duration, refreshFunc func(key string) (T, error)) *Cache[T] {
return &Cache[T]{
ttl: ttl,
store: make(map[string]CacheValue[T]),
refresh: refreshFunc,
}
}
func (c *Cache[T]) Get(key string) (T, error) {
v, ok := c.store[key]
if !ok || v.createdAt.Add(c.ttl).Before(time.Now()) {
if c.refresh != nil {
newVal, err := c.refresh(key)
if err != nil {
return *(new(T)), err
}
v = CacheValue[T]{newVal, time.Now()}
c.store[key] = v
return newVal, nil
} else {
return *(new(T)), errors.New("not found")
}
} else {
return v.val, nil
}
}
func (c *Cache[T]) Has(key string) bool {
val, ok := c.store[key]
if ok && val.createdAt.Add(c.ttl).Before(time.Now()) {
// present but expired
return false
}
return ok
}
func (c *Cache[T]) Store(key string, val T) {
c.store[key] = CacheValue[T]{val, time.Now()}
}