-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathrate-limiter.go
51 lines (43 loc) · 1.12 KB
/
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
package main
import (
"fmt"
"time"
"github.com/gomodule/redigo/redis"
)
// RateLimiter -
type RateLimiter struct {
pool *redis.Pool
}
// NewRateLimiter returns new instance of RateLimiter
func NewRateLimiter(pool *redis.Pool) *RateLimiter {
return &RateLimiter{pool: pool}
}
// Limit -
func (r *RateLimiter) Limit(token int64, onsuccess, onFirstFailure, onFailure func() error) error {
conn := r.pool.Get()
defer conn.Close()
minute := time.Now().Minute()
key := fmt.Sprintf("rate/%d/%d", token, minute)
resp, err := conn.Do("INCR", key)
if err != nil {
panic(err)
}
if count, ok := resp.(int64); ok {
if count == 1 {
conn.Do("EXPIRE", key, "60")
}
if count < 11 {
err := onsuccess()
return err
}
if count == 11 {
log.Infof("RateLimiter: Limit: first time limit exceeded for token (%d), tries: %d, minute: %d", token, count, minute)
err := onFirstFailure()
return err
}
log.Infof("RateLimiter: Limit: limit exceeded for token (%d), tries: %d, minute: %d", token, count, minute)
onFailure()
return err
}
return fmt.Errorf("RateLimiter: Limit: Redis returned wrong type: %T", resp)
}