-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspeedBump.go
78 lines (62 loc) · 1.63 KB
/
speedBump.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
package speedBump
import (
"net"
"net/http"
"strings"
"time"
)
type Option func(limiter *rateLimit)
type KeyFunc func(r *http.Request) (string, error)
func Limit(requestLimit int, windowLength time.Duration, options ...Option) func(next http.Handler) http.Handler {
return NewRateLimiter(requestLimit, windowLength, options...).Handler
}
func LimitAll(requestLimit int, windowLength time.Duration) func(next http.Handler) http.Handler {
return Limit(requestLimit, windowLength)
}
func LimitByIP(requestLimit int, windowLength time.Duration) func(next http.Handler) http.Handler {
return Limit(requestLimit, windowLength, WithKeyFuncs(KeyByIP))
}
func KeyByIP(r *http.Request) (string, error) {
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
ip = r.RemoteAddr
}
return ip, nil
}
func KeyByEndpoint(r *http.Request) (string, error) {
return r.URL.Path, nil
}
func WithKeyFuncs(keyFuncs ...KeyFunc) Option {
return func(limiter *rateLimit) {
if len(keyFuncs) > 0 {
limiter.keyFn = composeKeyFn(keyFuncs...)
}
}
}
func composeKeyFn(keyFuncs ...KeyFunc) KeyFunc {
return func(r *http.Request) (string, error) {
var key strings.Builder
for _, fn := range keyFuncs {
k, err := fn(r)
if err != nil {
return "", err
}
key.WriteString(k)
key.WriteRune(':')
}
return key.String(), nil
}
}
func WithLimitHandler(h http.HandlerFunc) Option {
return func(limiter *rateLimit) {
limiter.onRequestLimit = h
}
}
func WithLimitCounter(counter LimitCounter) Option {
return func(limiter *rateLimit) {
limiter.limitCounter = counter
}
}
func WithNoop() Option {
return func(limiter *rateLimit) {}
}