forked from ahmedash95/ratelimit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blocker.go
50 lines (43 loc) · 787 Bytes
/
blocker.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
package ratelimit
import "time"
type Block struct {
ExpiredAt time.Time
}
type Blocker struct {
Duration time.Duration
Values map[string]*Block
}
func CreateBlocker() Blocker {
b := Blocker{
Duration: time.Hour * 24,
Values: make(map[string]*Block),
}
BlockerCleaner(&b)
return b
}
func (s Blocker) AddIfNotExists(key string) {
_, ok := s.Values[key]
if !ok {
s.Values[key] = createBlock(s.Duration)
}
}
func createBlock(d time.Duration) *Block {
return &Block{
ExpiredAt: time.Now().Add(d),
}
}
func BlockerCleaner(l *Blocker) {
go func(l *Blocker) {
for {
time.Sleep(time.Second)
now := time.Now()
Mutex.Lock()
for k, r := range l.Values {
if r.ExpiredAt.Before(now) {
delete(l.Values, k)
}
}
Mutex.Unlock()
}
}(l)
}