/
ratelimiterflags.go
86 lines (72 loc) · 1.77 KB
/
ratelimiterflags.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
package main
import (
"errors"
"strconv"
"strings"
"time"
"github.com/zalando/skipper/ratelimit"
)
const ratelimitUsage = `set global rate limit settings, e.g. -ratelimit type=local,max-hits=20,time-window=60s
possible ratelimit properties:
type: local/service/disabled (defaults to disabled)
max-hits: the number of hits a ratelimiter can get
time-window: the duration of the sliding window for the rate limiter
(see also: https://godoc.org/github.com/zalando/skipper/ratelimit)`
const enableRatelimitUsage = `enable ratelimit`
type ratelimitFlags []ratelimit.Settings
var errInvalidRatelimitConfig = errors.New("invalid ratelimit config")
func (r *ratelimitFlags) String() string {
if r == nil {
return ""
}
s := make([]string, len(*r))
for i, ri := range *r {
s[i] = ri.String()
}
return strings.Join(s, "\n")
}
func (r *ratelimitFlags) Set(value string) error {
var s ratelimit.Settings
vs := strings.Split(value, ",")
for _, vi := range vs {
kv := strings.Split(vi, "=")
if len(kv) != 2 {
return errInvalidRatelimitConfig
}
switch kv[0] {
case "type":
switch kv[1] {
case "local":
fallthrough
case "client":
s.Type = ratelimit.ClientRatelimit
case "service":
s.Type = ratelimit.ServiceRatelimit
case "disabled":
s.Type = ratelimit.DisableRatelimit
default:
return errInvalidRatelimitConfig
}
case "max-hits":
i, err := strconv.Atoi(kv[1])
if err != nil {
return err
}
s.MaxHits = i
case "time-window":
d, err := time.ParseDuration(kv[1])
if err != nil {
return err
}
s.TimeWindow = d
s.CleanInterval = d * 10
default:
return errInvalidRatelimitConfig
}
}
if s.Type == ratelimit.NoRatelimit {
s.Type = ratelimit.DisableRatelimit
}
*r = append(*r, s)
return nil
}