This repository has been archived by the owner on Apr 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconcurrent_limiter.go
161 lines (151 loc) · 3.39 KB
/
concurrent_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
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
// Copyright 2018 tree xie
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package concurrentlimiter
import (
"errors"
"net/http"
"strings"
jsoniter "github.com/json-iterator/go"
"github.com/vicanso/elton"
"github.com/vicanso/hes"
)
var (
// errSubmitTooFrequently submit too frequently
errSubmitTooFrequently = &hes.Error{
StatusCode: http.StatusBadRequest,
Message: "submit too frequently",
Category: ErrCategory,
}
errRequireLockFunction = errors.New("require lock function")
json = jsoniter.ConfigCompatibleWithStandardLibrary
)
const (
ipKey = ":ip"
headerKey = "h:"
queryKey = "q:"
paramKey = "p:"
// ErrCategory concurrent limiter error category
ErrCategory = "elton-concurrent-limiter"
)
type (
// Lock lock the key
Lock func(string, *elton.Context) (bool, func(), error)
// Config concurrent limiter config
Config struct {
// Keys keys for generate lock id
Keys []string
// Lock lock function
Lock Lock
Skipper elton.Skipper
}
// keyInfo the concurrent key's info
keyInfo struct {
Name string
Params bool
Query bool
Header bool
Body bool
IP bool
}
)
// New create a concurrent limiter middleware
func New(config Config) elton.Handler {
if config.Lock == nil {
panic(errRequireLockFunction)
}
keys := make([]*keyInfo, 0)
// 根据配置生成key的处理
for _, key := range config.Keys {
if key == ipKey {
keys = append(keys, &keyInfo{
IP: true,
})
continue
}
if strings.HasPrefix(key, headerKey) {
keys = append(keys, &keyInfo{
Name: key[2:],
Header: true,
})
continue
}
if strings.HasPrefix(key, queryKey) {
keys = append(keys, &keyInfo{
Name: key[2:],
Query: true,
})
continue
}
if strings.HasPrefix(key, paramKey) {
keys = append(keys, &keyInfo{
Name: key[2:],
Params: true,
})
continue
}
keys = append(keys, &keyInfo{
Name: key,
Body: true,
})
}
skipper := config.Skipper
if skipper == nil {
skipper = elton.DefaultSkipper
}
keyLength := len(keys)
return func(c *elton.Context) (err error) {
if skipper(c) {
return c.Next()
}
sb := new(strings.Builder)
// 先申请假定每个value的长度
sb.Grow(8 * keyLength)
// 获取 lock 的key
for i, key := range keys {
v := ""
name := key.Name
if key.IP {
v = c.RealIP()
} else if key.Header {
v = c.GetRequestHeader(name)
} else if key.Query {
query := c.Query()
v = query[name]
} else if key.Params {
v = c.Param(name)
} else {
body := c.RequestBody
v = json.Get(body, name).ToString()
}
sb.WriteString(v)
if i < keyLength-1 {
sb.WriteRune(',')
}
}
lockKey := sb.String()
success, unlock, err := config.Lock(lockKey, c)
if err != nil {
err = hes.Wrap(err)
return
}
if !success {
err = errSubmitTooFrequently
return
}
if unlock != nil {
defer unlock()
}
return c.Next()
}
}