-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
cache.go
68 lines (60 loc) · 1.23 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
package memogram
import (
"sync"
"time"
)
// Cache is a simple cache implementation
type Cache struct {
sync.RWMutex
items map[string]*CacheItem
}
type CacheItem struct {
Value interface{}
Expiration time.Time
}
func NewCache() *Cache {
return &Cache{
items: make(map[string]*CacheItem),
}
}
// set adds a key value pair to the cache with a given duration
func (c *Cache) set(key string, value interface{}, duration time.Duration) {
c.Lock()
defer c.Unlock()
c.items[key] = &CacheItem{
Value: value,
Expiration: time.Now().Add(duration),
}
}
// get returns a value from the cache if it exists
func (c *Cache) get(key string) (interface{}, bool) {
c.RLock()
defer c.RUnlock()
item, found := c.items[key]
if !found {
return nil, false
}
if time.Now().After(item.Expiration) {
return nil, false
}
return item.Value, true
}
// deleteExpired deletes all expired key value pairs
func (c *Cache) deleteExpired() {
c.Lock()
defer c.Unlock()
for k, v := range c.items {
if time.Now().After(v.Expiration) {
delete(c.items, k)
}
}
}
// startGC starts a goroutine to clean expired key value pairs
func (c *Cache) startGC() {
go func() {
for {
<-time.After(5 * time.Minute)
c.deleteExpired()
}
}()
}