-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_parameter_limiter.go
65 lines (57 loc) · 1.35 KB
/
get_parameter_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
package rlutils
import (
"net/http"
"time"
"github.com/2manymws/rl"
)
type GetParameterLimiter struct {
getParameters map[string]string
key string
BaseLimiter
}
// Getパラメーターごとにリクエスト数を制限する
// 制限単位はホスト名とGetパラメーター
func NewGetParameterLimiter(
getParameters map[string]string,
reqLimit int,
windowLen time.Duration,
key string,
onRequestLimit func(*rl.Context, string) http.HandlerFunc,
setter ...Option,
) (*GetParameterLimiter, error) {
err := validateKey(key)
if err != nil {
return nil, err
}
return &GetParameterLimiter{
getParameters: getParameters,
key: key,
BaseLimiter: NewBaseLimiter(
reqLimit,
windowLen,
onRequestLimit,
setter...,
),
}, nil
}
func (l *GetParameterLimiter) Name() string {
return "get_parameter_limiter"
}
func (l *GetParameterLimiter) Rule(r *http.Request) (*rl.Rule, error) {
if !l.IsTargetRequest(r) {
return &rl.Rule{ReqLimit: -1}, nil
}
for k, v := range l.getParameters {
if r.URL.Query().Get(k) == v {
return &rl.Rule{
Key: fillKey(r, l.key) + "/" + k + "=" + v,
ReqLimit: l.reqLimit,
WindowLen: l.windowLen,
}, nil
}
}
return &rl.Rule{ReqLimit: -1}, nil
}
func (l *GetParameterLimiter) OnRequestLimit(r *rl.Context) http.HandlerFunc {
return l.onRequestLimit(r, l.Name())
}