-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstore.go
62 lines (54 loc) · 1.03 KB
/
store.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
package main
import (
"time"
)
type Store struct {
data map[string][]byte
expires map[string]int64
}
var sharedInstance *Store = newStore()
func newStore() *Store {
s := new(Store)
s.data = map[string][]byte{}
s.expires = map[string]int64{}
return s
}
func GetSharedStore() *Store {
return sharedInstance
}
func (s *Store) Set(key string, value []byte) error {
copied := make([]byte, len(value), len(value))
copy(copied, value)
s.data[key] = copied
s.expires[key] = time.Now().Unix() + 300
return nil
}
func (s *Store) Get(key string) ([]byte, bool) {
timelimit, ok := s.expires[key]
if ok {
now := time.Now().Unix()
if now > timelimit {
delete(s.data, key)
delete(s.expires, key)
} else {
value, ok := s.data[key]
if ok {
s.expires[key] = now + 300
return value, ok
}
}
}
return nil, false
}
func (s *Store) Keys() ([]string, error) {
list := make([]string, 0, len(s.data))
i := 0
for key, _ := range s.data {
_, ok := s.Get(key)
if ok {
list[i] = key
i++
}
}
return list, nil
}