-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemory_cache.go
75 lines (66 loc) · 1.48 KB
/
memory_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
74
75
package gohttp
import "time"
func newMemoryCache() CacheProvider {
return &memoryCache{map[string]map[string]cacheItem{}}
}
type memoryCache struct {
cache map[string]map[string]cacheItem
}
type cacheItem struct {
data interface{}
createTime time.Time
expiration time.Duration
}
func (mc *memoryCache) Exists(key string) bool {
_, ok := mc.cache[key]
return ok
}
func (mc *memoryCache) HExists(key, field string) bool {
session, ok := mc.cache[key]
if !ok {
return false
}
item, ok := session[field]
if !ok {
return false
}
if item.expiration > 0 && !item.createTime.Add(item.expiration).After(time.Now()) {
delete(session, field)
return false
}
return ok
}
func (mc *memoryCache) HGet(key, field string) interface{} {
session, ok := mc.cache[key]
if !ok {
return false
}
item, ok := session[field]
if !ok {
return false
}
if item.expiration > 0 && !item.createTime.Add(item.expiration).After(time.Now()) {
delete(session, field)
return false
}
return item.data
}
func (mc *memoryCache) HSet(key, field string, value interface{}, expiration time.Duration) {
mc.cache[key][field] = cacheItem{value, time.Now(), expiration}
}
func (mc *memoryCache) HDelete(key, field string) bool {
session, ok := mc.cache[key]
if !ok {
return false
}
item, ok := session[field]
if !ok {
return false
}
if item.expiration > 0 && !item.createTime.Add(item.expiration).After(time.Now()) {
delete(session, field)
return false
}
delete(session, field)
return true
}