-
Notifications
You must be signed in to change notification settings - Fork 276
/
store_sync_map.go
63 lines (54 loc) · 1.19 KB
/
store_sync_map.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
package base64Captcha
import (
"sync"
"time"
)
// StoreSyncMap use sync.Map as store
type StoreSyncMap struct {
liveTime time.Duration
m *sync.Map
}
// NewStoreSyncMap new a instance
func NewStoreSyncMap(liveTime time.Duration) *StoreSyncMap {
return &StoreSyncMap{liveTime: liveTime, m: new(sync.Map)}
}
// smv a value type
type smv struct {
t time.Time
Value string
}
// newSmv create a instance
func newSmv(v string) *smv {
return &smv{t: time.Now(), Value: v}
}
// rmExpire remove expired items
func (s StoreSyncMap) rmExpire() {
expireTime := time.Now().Add(-s.liveTime)
s.m.Range(func(key, value interface{}) bool {
if sv, ok := value.(*smv); ok && sv.t.Before(expireTime) {
s.m.Delete(key)
}
return true
})
}
// Get get a string value
func (s StoreSyncMap) Set(id string, value string) {
s.rmExpire()
s.m.Store(id, newSmv(value))
}
// Set a string value
func (s StoreSyncMap) Get(id string, clear bool) string {
v, ok := s.m.Load(id)
if !ok {
return ""
}
s.m.Delete(id)
if sv, ok := v.(*smv); ok {
return sv.Value
}
return ""
}
// Verify check a string value
func (s StoreSyncMap) Verify(id, answer string, clear bool) bool {
return s.Get(id, clear) == answer
}