/
api_request.go
76 lines (62 loc) · 1.58 KB
/
api_request.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package redisdb
import (
"log"
"strconv"
"time"
"github.com/gomodule/redigo/redis"
)
const (
apiUserPrefix = "api_user:"
maxRequestsPerMin = 100
fixedWindow = 60 // start of minute to end of minute
)
// incrementKey increases the count by 1 if key is present.
// Creates a key, sets the value to 1 with an expiry if the key is missing.
func incrementKey(rdb redis.Conn, key string, seconds int) {
_, err := rdb.Do("INCR", key)
if err != nil {
log.Fatal("redis: unable to set count for key: ", key)
}
if seconds > 0 {
_, err = rdb.Do("EXPIRE", key, seconds)
if err != nil {
log.Fatal("redis: unable to set expiry for key: ", key)
}
}
}
// getKeyCount retrieves the key count
func getKeyCount(rdb redis.Conn, key string) int {
exists, err := redis.Int(rdb.Do("EXISTS", key))
if err != nil {
log.Fatal("redis: check key exists failed. key: ", key)
}
if exists == 0 {
return 0
}
count, err := redis.Int(rdb.Do("GET", key))
if err != nil {
log.Fatal("redis: unable to get count for key: ", key)
}
return count
}
// getKeyCount creates the key with prefix and suffix
func createKey(ip string, t time.Time) string {
return apiUserPrefix + ip + ":" + strconv.Itoa(t.Minute())
}
// AllowAPIRequest determines whether an API request should be allowed or not
func AllowAPIRequest(ip string) bool {
rdb := Rdbpool.Get()
defer rdb.Close()
t := time.Now()
key := createKey(ip, t)
n := getKeyCount(rdb, key)
if n >= maxRequestsPerMin {
return false
}
seconds := 0
if n == 0 {
seconds = fixedWindow - t.Second()
}
incrementKey(rdb, key, seconds)
return true
}