-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrequest_path_limiter.go
87 lines (78 loc) · 1.91 KB
/
request_path_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
package rlutils
import (
"net/http"
"strings"
"time"
"github.com/2manymws/rl"
)
type RequestPathLimiter struct {
requestPathContains []string
requestPathPrefixes []string
requestPathSuffixes []string
ignorePathContains []string
ignorePathPrefixes []string
ignorePathSuffixes []string
key string
BaseLimiter
}
// リクエストパスごとにリクエスト数を制限する
// 制限単位はホスト名 + リクエストパス
func NewRequestPathLimiter(
requestPathContains []string,
requestPathPrefixes []string,
requestPathSuffixes []string,
reqLimit int,
windowLen time.Duration,
key string,
onRequestLimit func(*rl.Context, string) http.HandlerFunc,
setter ...Option,
) (*RequestPathLimiter, error) {
err := validateKey(key)
if err != nil {
return nil, err
}
return &RequestPathLimiter{
requestPathContains: requestPathContains,
requestPathPrefixes: requestPathPrefixes,
requestPathSuffixes: requestPathSuffixes,
key: key,
BaseLimiter: NewBaseLimiter(
reqLimit,
windowLen,
onRequestLimit,
setter...,
),
}, nil
}
func (l *RequestPathLimiter) Name() string {
return "request_path_limiter"
}
func (l *RequestPathLimiter) Rule(r *http.Request) (*rl.Rule, error) {
if !l.IsTargetRequest(r) {
return &rl.Rule{ReqLimit: -1}, nil
}
for _, st := range []struct {
path []string
f func(string, string) bool
}{
{l.requestPathPrefixes, strings.HasPrefix},
{l.requestPathSuffixes, strings.HasSuffix},
{l.requestPathContains, strings.Contains},
} {
if len(st.path) > 0 {
for _, path := range st.path {
if st.f(r.URL.Path, path) {
return &rl.Rule{
Key: fillKey(r, l.key) + path,
ReqLimit: l.reqLimit,
WindowLen: l.windowLen,
}, nil
}
}
}
}
return &rl.Rule{ReqLimit: -1}, nil
}
func (l *RequestPathLimiter) OnRequestLimit(r *rl.Context) http.HandlerFunc {
return l.onRequestLimit(r, l.Name())
}