Repository navigation
Expand file tree
/
Copy pathinmemory.go
More file actions
101 lines (81 loc) · 2.18 KB
/
Copy pathinmemory.go
File metadata and controls
101 lines (81 loc) · 2.18 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package cache
import (
"bytes"
"context"
"encoding/gob"
"fmt"
"time"
gocache "github.com/patrickmn/go-cache"
)
func NewInMemoryCache(expiration time.Duration) *InMemoryCache {
return &InMemoryCache{
memCache: gocache.New(expiration, 1*time.Minute),
}
}
// compile-time validation of adherance of the CacheClient contract
var _ CacheClient = &InMemoryCache{}
type InMemoryCache struct {
memCache *gocache.Cache
}
func (i *InMemoryCache) Set(item *Item) error {
var buf bytes.Buffer
err := gob.NewEncoder(&buf).Encode(item.Object)
if err != nil {
return err
}
i.memCache.Set(item.Key, buf, item.Expiration)
return nil
}
// HasSame returns true if key with the same value already present in cache
func (i *InMemoryCache) HasSame(key string, obj interface{}) (bool, error) {
var buf bytes.Buffer
err := gob.NewEncoder(&buf).Encode(obj)
if err != nil {
return false, err
}
bufIf, found := i.memCache.Get(key)
if !found {
return false, nil
}
existingBuf, ok := bufIf.(bytes.Buffer)
if !ok {
panic(fmt.Errorf("InMemoryCache has unexpected entry: %v", existingBuf))
}
return bytes.Equal(buf.Bytes(), existingBuf.Bytes()), nil
}
func (i *InMemoryCache) Get(key string, obj interface{}) error {
bufIf, found := i.memCache.Get(key)
if !found {
return ErrCacheMiss
}
buf := bufIf.(bytes.Buffer)
return gob.NewDecoder(&buf).Decode(obj)
}
func (i *InMemoryCache) Delete(key string) error {
i.memCache.Delete(key)
return nil
}
func (i *InMemoryCache) Flush() {
i.memCache.Flush()
}
func (i *InMemoryCache) OnUpdated(ctx context.Context, key string, callback func() error) error {
return nil
}
func (i *InMemoryCache) NotifyUpdated(key string) error {
return nil
}
// Items return a list of items in the cache; requires passing a constructor function
// so that the items can be decoded from gob format.
func (i *InMemoryCache) Items(createNewObject func() interface{}) (map[string]interface{}, error) {
result := map[string]interface{}{}
for key, value := range i.memCache.Items() {
buf := value.Object.(bytes.Buffer)
obj := createNewObject()
err := gob.NewDecoder(&buf).Decode(obj)
if err != nil {
return nil, err
}
result[key] = obj
}
return result, nil
}