-
Notifications
You must be signed in to change notification settings - Fork 1
/
in_memory_cache.go
90 lines (78 loc) · 1.84 KB
/
in_memory_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
80
81
82
83
84
85
86
87
88
89
90
package gocache
import (
"errors"
"strings"
"time"
)
// InMemoryCacheConfig struct
type InMemoryCacheConfig struct {
ExpiresIn time.Duration
}
type inMemoryCache struct {
keyValues map[string]string
keyRegistration map[string]time.Time
ExpiresIn time.Duration
}
// NewInMemoryCache new instance of inMemoryCache
func NewInMemoryCache(config InMemoryCacheConfig) *AdapterInterface {
if config.ExpiresIn <= 0 {
config.ExpiresIn = 3600 * time.Second
}
var adapter AdapterInterface = &inMemoryCache{
ExpiresIn: config.ExpiresIn,
}
return &adapter
}
func (n inMemoryCache) Get(key string) (string, error) {
if v, ok := n.keyValues[key]; ok && n.keyValues[key] != "" {
return v, nil
}
return "", errors.New("Cache not found")
}
func (n *inMemoryCache) Set(key string, value string) error {
if _, ok := n.keyValues[key]; !ok {
n.keyValues = map[string]string{}
}
if _, ok := n.keyRegistration[key]; !ok {
n.keyRegistration = map[string]time.Time{}
}
n.keyRegistration[key] = time.Now()
n.keyValues[key] = value
return nil
}
func (n inMemoryCache) IsValid(key string) bool {
if _, ok := n.keyValues[key]; ok && n.keyValues[key] != "" {
if _, ok := n.keyRegistration[key]; ok {
now := time.Now()
diff := now.Sub(n.keyRegistration[key])
if diff > n.ExpiresIn {
return false
}
}
return true
}
return false
}
func (n *inMemoryCache) Clear(key string) error {
if n.IsValid(key) {
delete(n.keyValues, key)
delete(n.keyRegistration, key)
}
return nil
}
func (n *inMemoryCache) ClearPrefix(keyPrefix string) error {
for v := range n.keyValues {
if strings.HasPrefix(v, keyPrefix) {
delete(n.keyValues, v)
delete(n.keyRegistration, v)
}
}
return nil
}
func (n *inMemoryCache) ClearAll() error {
for v := range n.keyValues {
delete(n.keyValues, v)
delete(n.keyRegistration, v)
}
return nil
}