-
Notifications
You must be signed in to change notification settings - Fork 1
/
spamguard.go
51 lines (46 loc) · 844 Bytes
/
spamguard.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
package main
import (
"sync"
"time"
)
type SpamGuard struct {
duration time.Duration
posts map[string]time.Time
mutex *sync.Mutex
}
func NewSpamGuard(duration string) *SpamGuard {
d, err := time.ParseDuration(duration)
if err != nil {
panic(err)
}
return &SpamGuard{
duration: d,
posts: make(map[string]time.Time),
mutex: &sync.Mutex{},
}
}
func (sg *SpamGuard) CanPost(id string) bool {
result := true
now := time.Now()
sg.mutex.Lock()
expires, found := sg.posts[id]
if found {
if expires.After(now) {
// Blocked
result = false
}
} else {
// Add to block
sg.posts[id] = now.Add(sg.duration)
}
sg.clean(now)
sg.mutex.Unlock()
return result
}
func (sg *SpamGuard) clean(now time.Time) {
for key, expires := range sg.posts {
if expires.Before(now) {
delete(sg.posts, key)
}
}
}