/
adt_route.go
248 lines (186 loc) · 5.01 KB
/
adt_route.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
package webserver
import (
"bytes"
"net/http"
"strings"
)
type routesByPattern map[string][]route
type route struct {
dynamicHost [][]byte
staticPattern string
dynamicPattern [][]byte
methods []string
handler Handler
}
var slashSlice = []byte{'/'}
var dotSlice = []byte{'.'}
var emptySlice = make([]byte, 0)
var emptyMatrix = make([][]byte, 0)
const dynamicSymbols = "{*"
func (this *routesByPattern) getRoute(method, pattern, hostPort, path string) (currentRoute *route, params map[string]string) {
routes := (*this)[pattern]
errorStatus := http.StatusNotFound
for _, route := range routes {
params, status := route.matchURLAndGetParam(hostPort, path)
if !status {
continue
}
if !route.acceptsMethod(method) {
errorStatus = http.StatusMethodNotAllowed
continue
}
return &route, params
}
NewHTTPError(errorStatus, nil).Panic()
// Should not reach here
return nil, nil
}
func (this *routesByPattern) Add(methods []string, pattern string, handler Handler) *route {
route := newRoute(methods, pattern, handler)
(*this)[route.staticPattern] = append((*this)[route.staticPattern], *route)
return route
}
func newRoute(methods []string, pattern string, handler Handler) *route {
route := &route{}
route.handler = handler
route.methods = methods
route.extractAndSetPattern([]byte(pattern))
return route
}
func (this *route) extractAndSetPattern(pattern []byte) {
// === DYNAMIC HOST === //
indexOf := bytes.IndexByte(pattern, '/')
if indexOf == -1 {
this.dynamicHost = bytes.Split(pattern, dotSlice)
reversePattern(this.dynamicHost)
return
}
if indexOf > 0 {
this.dynamicHost = bytes.Split(pattern[:indexOf], dotSlice)
reversePattern(this.dynamicHost)
pattern = pattern[indexOf:]
}
// === STATIC AND DYNAMIC PATH PATTERN === //
indexOf = bytes.IndexAny(pattern, dynamicSymbols)
if indexOf == -1 {
this.staticPattern = string(trimSlashes(pattern))
return
}
dynamicPattern := pattern[indexOf:]
staticPattern := pattern[:indexOf]
staticPattern = staticPattern[:bytes.LastIndexByte(staticPattern, '/')+1]
this.staticPattern = string(trimSlashes(staticPattern))
this.dynamicPattern = bytes.Split(trimSlashes(dynamicPattern), slashSlice)
}
func (this *route) matchURLAndGetParam(hostPort, path string) (params map[string]string, status bool) {
params = make(map[string]string)
// Validate dynamic host
if len(this.dynamicHost) > 0 {
host, _ := splitHostPort(hostPort)
hostTokens := bytes.Split([]byte(host), dotSlice)
reversePattern(hostTokens)
if !matchTokens(this.dynamicHost, hostTokens, params) {
return nil, false
}
}
// The static part of the path was already validated by 'http' library
if len(path) == len(this.staticPattern) && len(this.dynamicPattern) == 0 {
return params, true
}
// Split dynamic part of the path by slashes
pathBytes := trimSlashes(trimSlashes([]byte(path))[len(this.staticPattern):])
var dynamicPath [][]byte
if len(pathBytes) > 0 {
dynamicPath = bytes.Split(pathBytes, slashSlice)
} else {
dynamicPath = emptyMatrix
}
// Validate dynamic path
return params, matchTokens(this.dynamicPattern, dynamicPath, params)
}
func matchTokens(tokensPattern, tokens [][]byte, params map[string]string) bool {
tokensLength := len(tokens)
for index, key := range tokensPattern {
var hasToken bool = index < tokensLength
var tokenValue []byte
if hasToken {
tokenValue = tokens[index]
}
switch key[0] {
// case '*': ignore
case '*':
// case '**': ignore all
if len(key) > 1 && key[1] == '*' {
return true
}
// case '{': parse param and validate
case '{':
name, isOptional := parsePathParam(key, tokenValue)
if !hasToken {
return isOptional
}
params[string(name)] = string(tokenValue)
// default: compare static names
default:
if bytes.Compare(key, tokenValue) != 0 {
return false
}
}
}
return len(tokensPattern) >= tokensLength
}
func parsePathParam(pattern, path []byte) (name []byte, isOpt bool) {
isOpt = isOptional(pattern)
if !isOpt && len(path) == 0 {
return nil, isOpt
}
end := len(pattern) - 1
if isOpt {
end--
}
return pattern[1:end], isOpt
}
func isOptional(pattern []byte) bool {
tokenIndex := len(pattern) - 2
if tokenIndex < 2 {
return false
}
return pattern[tokenIndex] == '?'
}
func trimSlashes(data []byte) []byte {
begin, end := 0, len(data)
if end == 0 {
return data
}
if data[begin] == '/' {
begin++
}
if end > 1 && data[end-1] == '/' {
end--
}
return data[begin:end]
}
func (this *route) acceptsMethod(method string) bool {
if this.methods == nil {
return true
}
for _, item := range this.methods {
if item == method {
return true
}
}
return false
}
func splitHostPort(hostPort string) (host, port string) {
host = hostPort
colon := strings.LastIndexByte(host, ':')
if colon == -1 {
return host, ""
}
return hostPort[:colon], hostPort[colon+1:]
}
func reversePattern(pattern [][]byte) {
for i, j := 0, len(pattern)-1; i < j; i, j = i+1, j-1 {
pattern[i], pattern[j] = pattern[j], pattern[i]
}
}