-
Notifications
You must be signed in to change notification settings - Fork 0
/
limiter.go
60 lines (49 loc) · 913 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* Package main
* @Author iFurySt <ifuryst@gmail.com>
* @Date 2024/5/9
*/
package main
import (
"sync"
"time"
)
type RateLimiter struct {
rate Rate
mu sync.Mutex
last time.Time
counts int
}
func NewLimiter(rate Rate) RateLimiter {
return RateLimiter{
rate: rate,
}
}
func (rl *RateLimiter) Allow() bool {
if rl.rate.Number == 0 {
return true
}
now := time.Now()
switch rl.rate.Unit {
case RateUnitSecond:
return rl.allow(now, time.Second)
case RateUnitMinute:
return rl.allow(now, time.Minute)
case RateUnitHour:
return rl.allow(now, time.Hour)
}
return false
}
func (rl *RateLimiter) allow(now time.Time, period time.Duration) bool {
rl.mu.Lock()
defer rl.mu.Unlock()
if now.Sub(rl.last) >= period {
rl.resetCounts(now)
}
rl.counts++
return rl.counts <= rl.rate.Number
}
func (rl *RateLimiter) resetCounts(t time.Time) {
rl.counts = 0
rl.last = t
}