-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
53 lines (43 loc) · 870 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
Value interface{}
Expiration int64
}
type Cache struct {
items map[string]CacheItem
mu sync.RWMutex
}
func (c *Cache) Set(key string, value interface{}, duration time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
expiration := time.Now().Add(duration).UnixNano()
c.items[key] = CacheItem{
Key: key,
Value: value,
Expiration: expiration,
}
}
func (c *Cache) Get(key string) (interface{}, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
item, found := c.items[key]
if !found || item.Expiration < time.Now().UnixNano() {
return nil, false
}
return item.Value, true
}
func (c *Cache) Delete(key string) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.items, key)
}
func NewCache() *Cache {
return &Cache{
items: make(map[string]CacheItem),
}
}