forked from ahmedash95/ratelimit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pattern_parser.go
82 lines (71 loc) · 1.68 KB
/
pattern_parser.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
package ratelimit
import (
"fmt"
"strconv"
"strings"
"time"
)
type Options struct {
Max int
Per time.Duration
Block time.Duration
MaxToSpam int
}
func parse(s string) (Options, error) {
op := Options{}
parsed := strings.Split(s, ",")
p := strings.Split(parsed[0], "r/")
maxValue, _ := strconv.Atoi(p[0])
if maxValue < 1 {
return op, fmt.Errorf("Invalid max requests value [%d] must be larger than zero", maxValue)
}
per := p[1]
if per != "s" && per != "m" {
return op, fmt.Errorf("Invalid limit [%s] Limit must be per s as second or m as minute", per)
}
perDuration := time.Second
if per == "m" {
perDuration = time.Minute
}
op.Max = maxValue
op.Per = perDuration
for _, p := range parsed[1:] {
s := strings.Split(p, ":")
if len(s) != 2 {
return op, fmt.Errorf("Can't parse value: %s", p)
}
if s[0] != "spam" && s[0] != "block" {
return op, fmt.Errorf("Unsupported module [%s] must be spam or block", s[0])
}
if s[0] == "spam" {
value, _ := strconv.Atoi(s[1])
op.MaxToSpam = value
}
if s[0] == "block" {
v := s[1]
max, _ := strconv.Atoi(v[:len(v)-1])
duration := v[len(v)-1:]
if duration != "d" && duration != "h" && duration != "m" && duration != "s" {
return op, fmt.Errorf("Unsupported time duration [%s] must be (d) for day, (h) for hour, (m) for minute or (s) for second.", duration)
}
op.Block = getDuration(max, duration)
} else {
op.Block = 0
}
}
return op, nil
}
func getDuration(max int, s string) time.Duration {
t := time.Second
switch s {
case "d":
t = time.Hour * 24
case "h":
t = time.Hour
case "m":
t = time.Minute
default:
t = time.Second
}
return time.Duration(max) * t
}