-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.go
274 lines (228 loc) · 6.25 KB
/
trie.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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package art
import (
"errors"
"fmt"
"reflect"
"runtime"
"sort"
"unsafe"
)
// middleware 只會用在 handler 和 defaultHandler
// handle message 執行順序, 依照號碼 0~3
type paramHandler struct {
// any
middlewares []Middleware
// 0
transform HandleFunc
// 1
handler HandleFunc
handlerName string
// 2
defaultHandler HandleFunc
defaultHandlerName string
// 3
notFoundHandler HandleFunc
}
func (param *paramHandler) register(leafNode *trie, path []Middleware) error {
if param.middlewares != nil {
leafNode.middlewares = append(leafNode.middlewares, param.middlewares...)
}
if param.transform != nil {
if leafNode.transform != nil {
return errors.New("assign duplicated transform")
}
leafNode.transform = param.transform
}
if param.handler != nil {
if leafNode.handler != nil {
return errors.New("assign duplicated handler")
}
leafNode.handler = Link(param.handler, path...)
if param.handlerName == "" {
leafNode.handlerName = functionName(param.handler)
} else {
leafNode.handlerName = param.handlerName
}
}
if param.defaultHandler != nil {
if leafNode.defaultHandler != nil {
return errors.New("assign duplicated defaultHandler")
}
leafNode.defaultHandler = Link(param.defaultHandler, path...)
if param.defaultHandlerName == "" {
leafNode.defaultHandlerName = functionName(param.defaultHandler)
} else {
leafNode.defaultHandlerName = param.defaultHandlerName
}
}
if param.notFoundHandler != nil {
if leafNode.notFoundHandler != nil {
return errors.New("assign duplicated notFoundHandler")
}
leafNode.notFoundHandler = param.notFoundHandler
}
return nil
}
func functionName(fn any) string {
return runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name()
}
func newTrie(delimiter string) *trie {
return &trie{
staticChild: make(map[byte]*trie),
delimiter: delimiter,
}
}
type trie struct {
staticChild map[byte]*trie // key : value => char : child
wildcardChildWord string
wildcardChild *trie
delimiter string
fullSubject string
paramHandler
}
func (node *trie) addRoute(subject string, cursor int, param *paramHandler, path []Middleware) *trie {
if node.middlewares != nil {
path = append(path, node.middlewares...)
}
if len(subject) == cursor {
if param == nil { // for Mux.Group
param = ¶mHandler{
middlewares: path,
}
}
leafNode := node
err := param.register(leafNode, path)
if err != nil {
Err := fmt.Errorf("subject=%q: %w", subject, err)
panic(Err)
}
return leafNode
}
char := subject[cursor]
if char != '{' {
child, exist := node.staticChild[char]
if !exist {
child = newTrie(node.delimiter)
child.fullSubject = node.fullSubject + string(char)
node.staticChild[char] = child
}
return child.addRoute(subject, cursor+1, param, path)
}
if node.delimiter == "" {
err := fmt.Errorf("subject=%q: route delimiter is empty: not support wildcard", subject)
panic(err)
}
idx := cursor
for idx < len(subject) && subject[idx] != '}' {
idx++
}
if subject[idx] != '}' {
err := fmt.Errorf("subject=%q: lack wildcard '}'", subject)
panic(err)
}
if node.wildcardChild != nil {
if node.wildcardChildWord != subject[cursor+1:idx] {
err := fmt.Errorf("subject=%q: assign duplicated wildcard: %q", node.wildcardChild.fullSubject, subject)
panic(err)
}
return node.wildcardChild.addRoute(subject, idx+1, param, path)
}
child := newTrie(node.delimiter)
child.fullSubject = node.fullSubject + subject[cursor:idx+1] // {word}, include {}
node.wildcardChildWord = subject[cursor+1 : idx] // word, exclude {}
node.wildcardChild = child
return child.addRoute(subject, idx+1, param, path)
}
func (node *trie) handleMessage(subject string, cursor int, message *Message, dep any) error {
current := node
var defaultHandler, notFoundHandler HandleFunc
const notWildcard = -1
wildcardStart := notWildcard
var wildcardParent *trie
for cursor <= len(subject) {
if current.transform != nil {
err := current.transform(message, dep)
if err != nil {
return err
}
subject = message.Subject
}
if current.defaultHandler != nil {
defaultHandler = current.defaultHandler
}
if current.notFoundHandler != nil {
notFoundHandler = current.notFoundHandler
}
if current.wildcardChild != nil {
wildcardStart = cursor
wildcardParent = current
}
if cursor == len(subject) {
break
}
child, exist := current.staticChild[subject[cursor]]
if !exist {
break
}
cursor++
current = child
}
// for static route
if current.handler != nil {
return current.handler(message, dep)
}
if wildcardParent == nil {
if defaultHandler != nil {
return defaultHandler(message, dep)
}
if notFoundHandler != nil {
return notFoundHandler(message, dep)
}
return ErrNotFoundSubject
}
// for wildcard route
wildcardFinish := wildcardStart
for wildcardFinish < len(subject) && subject[wildcardFinish] != current.delimiter[0] {
wildcardFinish++
}
bytes := unsafe.Slice(unsafe.StringData(subject), len(subject))
value := bytes[wildcardStart:wildcardFinish]
str := unsafe.String(unsafe.SliceData(value), wildcardFinish-wildcardStart)
message.RouteParam.Set(wildcardParent.wildcardChildWord, str)
// message.RouteParam.Set(wildcardParent.wildcardChildWord, subject[wildcardStart:wildcardFinish])
err := wildcardParent.wildcardChild.handleMessage(subject, wildcardFinish, message, dep)
if err != nil && errors.Is(err, ErrNotFoundSubject) {
if defaultHandler != nil {
return defaultHandler(message, dep)
}
if notFoundHandler != nil {
return notFoundHandler(message, dep)
}
return ErrNotFoundSubject
}
return err
}
// pair = [subject, function]
func (node *trie) endpoint() (pairs [][2]string) {
pairs = make([][2]string, 0)
node._endpoint_(&pairs)
sort.SliceStable(pairs, func(i, j int) bool {
return pairs[i][0] < pairs[j][0]
})
return
}
func (node *trie) _endpoint_(paris *[][2]string) {
if node.handler != nil {
*paris = append(*paris, [2]string{node.fullSubject, node.handlerName})
}
if node.defaultHandler != nil {
*paris = append(*paris, [2]string{node.fullSubject + ".*", node.defaultHandlerName})
}
for _, next := range node.staticChild {
next._endpoint_(paris)
}
if node.wildcardChild == nil {
return
}
node.wildcardChild._endpoint_(paris)
}