forked from panco95/go-garden
/
limiter.go
61 lines (52 loc) · 1.18 KB
/
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
package core
import (
"errors"
"strconv"
"strings"
"sync/atomic"
"time"
)
type limiterData struct {
StartTimestamp int64
Quantity int64
}
func limiterAnalyze(limiter string) (int64, int64, error) {
arr := strings.Split(limiter, "/")
if len(arr) != 2 {
return 0, 0, errors.New("route limiter format error")
}
second, err := strconv.Atoi(arr[0])
if err != nil {
return 0, 0, errors.New("route limiter format error")
}
quantity, err := strconv.Atoi(arr[1])
if err != nil {
return 0, 0, errors.New("route limiter format error")
}
return int64(second), int64(quantity), nil
}
func (g *Garden) limiterInspect(path string, second, quantity int64) bool {
l, ok := g.limiterMap.Load(path)
if !ok {
l = g.resetLimiterIndex(path)
}
ld := l.(*limiterData)
now := time.Now().Unix()
lost := now - ld.StartTimestamp
if lost >= second {
ld = g.resetLimiterIndex(path)
}
if atomic.LoadInt64(&ld.Quantity) >= quantity {
return false
}
atomic.AddInt64(&ld.Quantity, 1)
return true
}
func (g *Garden) resetLimiterIndex(index string) *limiterData {
ld := limiterData{
StartTimestamp: time.Now().Unix(),
Quantity: 0,
}
g.limiterMap.Store(index, &ld)
return &ld
}