-
Notifications
You must be signed in to change notification settings - Fork 0
/
limiter.go
42 lines (34 loc) · 869 Bytes
/
limiter.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
package main
import (
"sync"
"time"
mlimiters "github.com/mennanov/limiters"
"github.com/mgjules/chat-demo/user"
)
type limiters struct {
mu sync.RWMutex
limiters map[string]*mlimiters.TokenBucket
}
func newLimiters() *limiters {
return &limiters{
limiters: make(map[string]*mlimiters.TokenBucket),
}
}
func (l *limiters) add(u *user.User, d time.Duration, b int64) *mlimiters.TokenBucket {
l.mu.RLock()
limiter, found := l.limiters[u.ID.String()]
l.mu.RUnlock()
if found {
return limiter
}
limiter = mlimiters.NewTokenBucket(b, d, mlimiters.NewLockNoop(), mlimiters.NewTokenBucketInMemory(), mlimiters.NewSystemClock(), mlimiters.NewStdLogger())
l.mu.Lock()
l.limiters[u.ID.String()] = limiter
l.mu.Unlock()
return limiter
}
func (l *limiters) remove(u *user.User) {
l.mu.Lock()
delete(l.limiters, u.ID.String())
l.mu.Unlock()
}