-
Notifications
You must be signed in to change notification settings - Fork 10
/
spammer.go
54 lines (47 loc) · 835 Bytes
/
spammer.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
package ratelimit
import "time"
type Spam struct {
ExpiredAt time.Time
Hits int
}
type Spammer struct {
Duration time.Duration
Values map[string]*Spam
}
func CreateSpammer() Spammer {
sp := Spammer{
Duration: time.Hour * 24,
Values: make(map[string]*Spam),
}
SpamCleaner(&sp)
return sp
}
func (s Spammer) Increase(key string) {
k, ok := s.Values[key]
if !ok {
s.Values[key] = createSpam(s.Duration)
k = s.Values[key]
}
k.Hits += 1
}
func createSpam(d time.Duration) *Spam {
return &Spam{
ExpiredAt: time.Now().Add(d),
Hits: 0,
}
}
func SpamCleaner(l *Spammer) {
go func(l *Spammer) {
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)
}