-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcountry_limiter.go
135 lines (114 loc) · 2.55 KB
/
country_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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package rlutils
// limit from ip with maxMindDB
import (
"fmt"
"net"
"net/http"
"strings"
"time"
"github.com/2manymws/rl"
maxminddb "github.com/oschwald/maxminddb-golang"
)
type CountryLimiter struct {
db *maxminddb.Reader
countries map[string]struct{}
skipCountries map[string]struct{}
BaseLimiter
}
type key int
const ContextCountryKey key = iota
// 国別のリクエスト数を制限する
// 制限単位はIPアドレス
func NewCountryLimiter(
dbPath string,
countries []string,
skipCountries []string,
reqLimit int,
windowLen time.Duration,
onRequestLimit func(*rl.Context, string) http.HandlerFunc,
setter ...Option,
) (*CountryLimiter, error) {
db, err := maxminddb.Open(dbPath)
if err != nil {
return nil, err
}
cm := map[string]struct{}{}
scm := map[string]struct{}{}
for _, c := range countries {
cm[c] = struct{}{}
}
for _, c := range skipCountries {
if c == "*" {
return nil, fmt.Errorf("invalid skip country: %s", c)
}
scm[c] = struct{}{}
}
return &CountryLimiter{
db: db,
countries: cm,
skipCountries: scm,
BaseLimiter: NewBaseLimiter(
reqLimit,
windowLen,
onRequestLimit,
setter...,
),
}, nil
}
func (l *CountryLimiter) Name() string {
return "country_limiter"
}
func (l *CountryLimiter) Rule(r *http.Request) (*rl.Rule, error) {
if !l.IsTargetRequest(r) {
return &rl.Rule{ReqLimit: -1}, nil
}
remoteAddr := strings.Split(r.RemoteAddr, ":")[0]
country := ""
if r.Context().Value(ContextCountryKey) != nil {
country = r.Context().Value(ContextCountryKey).(string)
} else {
c, err := l.country(remoteAddr)
if err != nil {
return nil, err
}
country = c
}
limit := &rl.Rule{
Key: remoteAddr,
ReqLimit: l.reqLimit,
WindowLen: l.windowLen,
}
noLimit := &rl.Rule{ReqLimit: -1}
if country == "" {
return noLimit, nil
}
if _, ok := l.skipCountries[country]; ok {
return noLimit, nil
}
if _, ok := l.countries["*"]; ok {
return limit, nil
}
if _, ok := l.countries[country]; ok {
return &rl.Rule{
Key: remoteAddr,
ReqLimit: l.reqLimit,
WindowLen: l.windowLen,
}, nil
}
return noLimit, nil
}
func (l *CountryLimiter) country(remoteAddr string) (string, error) {
var record struct {
Country struct {
ISOCode string `maxminddb:"iso_code"`
} `maxminddb:"country"`
}
err := l.db.Lookup(net.ParseIP(remoteAddr), &record)
if err != nil {
return "", err
}
return record.Country.ISOCode, nil
}
func (l *CountryLimiter) OnRequestLimit(r *rl.Context) http.HandlerFunc {
return l.onRequestLimit(r, l.Name())
}