forked from cloudfoundry-samples/ratelimit-service
/
rate_limiter.go
56 lines (46 loc) · 899 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
47
48
49
50
51
52
53
54
55
56
package main
import (
"fmt"
"time"
"github.com/cloudfoundry-samples/ratelimit-service/store"
)
type Stats []Stat
type Stat struct {
Ip string
Count int
}
type RateLimiter struct {
limit int
duration time.Duration
store store.Store
}
func NewRateLimiter(limit int, duration time.Duration) *RateLimiter {
return &RateLimiter{
limit: limit,
duration: duration,
store: store.NewStore(),
}
}
func (r *RateLimiter) ExceedsLimit(ip string) bool {
current := r.store.Increment(ip)
// if first request set expiry time
if current == 1 {
r.store.ExpiresIn(r.duration, ip)
}
// if exceeds limit
if current > r.limit {
fmt.Printf("rate limit exceeded for %s\n", ip)
return true
}
return false
}
func (r *RateLimiter) GetStats() Stats {
s := Stats{}
for k, v := range r.store.Current() {
s = append(s, Stat{
Ip: k,
Count: v,
})
}
return s
}