-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcache.go
More file actions
81 lines (66 loc) · 1.31 KB
/
cache.go
File metadata and controls
81 lines (66 loc) · 1.31 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
package rest
import (
"errors"
"sync"
"time"
)
type CacheError struct {
message string
}
func (c *CacheError) Error() string {
return c.message
}
type Cache interface {
Get(key string) (*DiscordResponse, error)
Put(key string, value *DiscordResponse) error
}
// Reference in-memory implementation
type MemoryCache struct {
sync.RWMutex
cacheMap map[string]*CacheValue
config *MemoryCacheConfig
cleanChan chan string
}
type CacheValue struct {
resp *DiscordResponse
// insertion time.Time
timer *time.Timer
}
type MemoryCacheConfig struct {
retention time.Duration
}
func NewMemoryCache() *MemoryCache {
cache := &MemoryCache{
cacheMap: make(map[string]*CacheValue),
cleanChan: make(chan string),
}
go cache.cleaner()
return cache
}
func (m *MemoryCache) Get(key string) (*DiscordResponse, error) {
m.RLock()
defer m.RUnlock()
data, ok := m.cacheMap[key]
if !ok {
return nil, errors.New("not found")
}
return data.resp, nil
}
func (m *MemoryCache) Put(key string, resp *DiscordResponse) error {
m.Lock()
defer m.Unlock()
m.cacheMap[key] = &CacheValue{
resp: resp,
timer: time.AfterFunc(m.config.retention, func() {
m.cleanChan <- key
}),
}
return nil
}
func (m *MemoryCache) cleaner() {
for key := range m.cleanChan {
m.Lock()
delete(m.cacheMap, key)
m.Unlock()
}
}