forked from ulule/limiter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rate.go
57 lines (45 loc) · 991 Bytes
/
rate.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
package limiter
import (
"fmt"
"strconv"
"strings"
"time"
)
// Rate is the rate.
type Rate struct {
Formatted string
Period time.Duration
Limit int64
}
// NewRateFromFormatted returns the rate from the formatted version.
func NewRateFromFormatted(formatted string) (Rate, error) {
rate := Rate{}
values := strings.Split(formatted, "-")
if len(values) != 2 {
return rate, fmt.Errorf("Incorrect format '%s'", formatted)
}
periods := map[string]time.Duration{
"S": time.Second, // Second
"M": time.Minute, // Minute
"H": time.Hour, // Hour
}
limit, period := values[0], strings.ToUpper(values[1])
duration, ok := periods[period]
if !ok {
return rate, fmt.Errorf("Incorrect period '%s'", period)
}
var (
p time.Duration
l int
)
p = 1 * duration
l, err := strconv.Atoi(limit)
if err != nil {
return rate, fmt.Errorf("Incorrect limit '%s'", limit)
}
return Rate{
Formatted: formatted,
Period: p,
Limit: int64(l),
}, nil
}