-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathip_limiter.go
51 lines (44 loc) · 950 Bytes
/
ip_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 rlutils
import (
"net/http"
"strings"
"time"
"github.com/2manymws/rl"
)
type IPLimiter struct {
BaseLimiter
}
// ホストごとにリクエスト数を制限する
// 制限単位はIP
func NewIPLimiter(
reqLimit int,
windowLen time.Duration,
targetExtensions []string,
onRequestLimit func(*rl.Context, string) http.HandlerFunc,
) *IPLimiter {
return &IPLimiter{
BaseLimiter: NewBaseLimiter(
reqLimit,
windowLen,
targetExtensions,
onRequestLimit,
),
}
}
func (l *IPLimiter) Name() string {
return "ip_limiter"
}
func (l *IPLimiter) Rule(r *http.Request) (*rl.Rule, error) {
if !l.IsTargetRequest(r) {
return &rl.Rule{ReqLimit: -1}, nil
}
remoteAddr := strings.Split(r.RemoteAddr, ":")[0]
return &rl.Rule{
Key: remoteAddr,
ReqLimit: l.reqLimit,
WindowLen: l.windowLen,
}, nil
}
func (l *IPLimiter) OnRequestLimit(r *rl.Context) http.HandlerFunc {
return l.onRequestLimit(r, l.Name())
}