-
Notifications
You must be signed in to change notification settings - Fork 0
/
rate_limiter.go
46 lines (39 loc) · 969 Bytes
/
rate_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
package ratelimiter
import (
"time"
)
type RateLimiter struct {
timestamps chan time.Time
capacity uint
duration time.Duration
}
// max request allowed capacity of the rate limiter and time period withing which all the requests hit for
func NewRateLimiter(capacity uint, duration time.Duration) *RateLimiter {
ra := &RateLimiter{
timestamps: make(chan time.Time, capacity),
capacity: capacity,
duration: duration,
}
go ra.consumer()
return ra
}
// push all the timestamps here and let limiter do its job
func (ra *RateLimiter) Push(value time.Time) {
go func() {
ra.timestamps <- value
}()
}
func (ra *RateLimiter) consumer() {
for {
tstamp := <-ra.timestamps
now := time.Now()
future := tstamp.Add(ra.duration)
if future.After(now) {
time.Sleep(future.Sub(now))
}
}
}
func (ra *RateLimiter) LimitReached() bool {
return len(ra.timestamps) == int(ra.capacity)
// https://groups.google.com/g/golang-nuts/c/L0wIBDr3HCc
}