forked from cyfdecyf/cow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeoutset.go
46 lines (40 loc) · 684 Bytes
/
timeoutset.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
package main
import (
"sync"
"time"
)
type TimeoutSet struct {
sync.RWMutex
time map[string]time.Time
timeout time.Duration
}
func NewTimeoutSet(timeout time.Duration) *TimeoutSet {
ts := &TimeoutSet{time: make(map[string]time.Time),
timeout: timeout,
}
return ts
}
func (ts *TimeoutSet) add(key string) {
now := time.Now()
ts.Lock()
ts.time[key] = now
ts.Unlock()
}
func (ts *TimeoutSet) has(key string) bool {
ts.RLock()
t, ok := ts.time[key]
ts.RUnlock()
if !ok {
return false
}
if time.Now().Sub(t) > ts.timeout {
ts.del(key)
return false
}
return true
}
func (ts *TimeoutSet) del(key string) {
ts.Lock()
delete(ts.time, key)
ts.Unlock()
}