forked from statping/statping
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
73 lines (62 loc) · 1.32 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
69
70
71
72
73
package handlers
import (
"sync"
"time"
)
var CacheStorage Cacher
type Cacher interface {
Get(key string) []byte
Delete(key string)
Set(key string, content []byte, duration time.Duration)
List() map[string]Item
}
// Item is a cached reference
type Item struct {
Content []byte
Expiration int64
}
// Expired returns true if the item has expired.
func (item Item) Expired() bool {
if item.Expiration == 0 {
return false
}
return time.Now().UnixNano() > item.Expiration
}
//Storage mecanism for caching strings in memory
type Storage struct {
items map[string]Item
mu *sync.RWMutex
}
//NewStorage creates a new in memory CacheStorage
func NewStorage() *Storage {
return &Storage{
items: make(map[string]Item),
mu: &sync.RWMutex{},
}
}
func (s Storage) List() map[string]Item {
return s.items
}
//Get a cached content by key
func (s Storage) Get(key string) []byte {
item := s.items[key]
if item.Expired() {
CacheStorage.Delete(key)
return nil
}
return item.Content
}
func (s Storage) Delete(key string) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.items, key)
}
//Set a cached content by key
func (s Storage) Set(key string, content []byte, duration time.Duration) {
s.mu.Lock()
defer s.mu.Unlock()
s.items[key] = Item{
Content: content,
Expiration: time.Now().Add(duration).UnixNano(),
}
}