-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcache.go
53 lines (44 loc) · 852 Bytes
/
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
package main
import (
"sync"
"time"
)
type CacheItem struct {
key string
val string
age int64
}
type Cache struct {
items map[string]CacheItem
lock *sync.RWMutex
maxAgeSec int64
}
func NewCache(maxAgeSeconds int64) *Cache {
return &Cache{
items: make(map[string]CacheItem, 1024),
lock: new(sync.RWMutex),
maxAgeSec: maxAgeSeconds,
}
}
func (c *Cache) Get(key string) string {
c.lock.RLock()
defer c.lock.RUnlock()
now := time.Now()
currTime := now.Unix()
if currTime-c.items[key].age > c.maxAgeSec {
return ""
}
return c.items[key].val
}
func (c *Cache) Add(key string, val string) {
c.lock.Lock()
defer c.lock.Unlock()
now := time.Now()
age := now.Unix()
c.items[key] = CacheItem{key, val, age}
}
func (c *Cache) Remove(id string) {
c.lock.Lock()
defer c.lock.Unlock()
delete(c.items, id)
}