This repository has been archived by the owner on Aug 2, 2018. It is now read-only.
/
path.go
407 lines (321 loc) · 6.59 KB
/
path.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
// Copyright 2016 Marcel Gotsch. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package goserv
import (
"bytes"
"fmt"
"regexp"
"strings"
"unicode"
)
type matcher interface {
Match(path string) bool
}
type allMatcher struct{}
func (a *allMatcher) Match(string) bool {
return true
}
type stringMatcher struct {
path string
strict bool
}
func (s *stringMatcher) Match(path string) bool {
if path != "/" && !s.strict && strings.HasSuffix(path, "/") {
path = path[:len(path)-1]
}
return s.path == path
}
type stringPrefixMatcher struct {
path string
}
func (s *stringPrefixMatcher) Match(path string) bool {
return strings.HasPrefix(path, s.path)
}
type regexpMatcher struct {
rx *regexp.Regexp
}
func (r *regexpMatcher) Match(path string) bool {
return r.rx.MatchString(path)
}
type path struct {
matcher
params *regexp.Regexp
names []string
}
func (p *path) ContainsParams() bool {
return len(p.names) > 0
}
func (p *path) Params() []string {
return p.names
}
func (p *path) FillParams(path string, params params) {
if !p.ContainsParams() {
return
}
matches := p.params.FindAllStringSubmatch(path, -1)
if len(matches) == 0 {
return
}
// Iterate group matches only
names := p.params.SubexpNames()[1:]
for index, value := range matches[0][1:] {
name := names[index]
// Skip unnamed groups
if len(name) == 0 {
continue
}
params[name] = value
}
}
type runeStream struct {
data []rune
idx int
}
func (r *runeStream) Err(msg string) error {
return fmt.Errorf("Error at index %d, %s", r.idx-1, msg)
}
func (r *runeStream) Peek() rune {
if r.AtEnd() {
panic("cannot peek after end")
}
return r.data[r.idx+1]
}
func (r *runeStream) Back() {
if r.idx == 0 {
return
}
r.idx--
}
func (r *runeStream) Next() rune {
if r.AtEnd() {
panic("cannot read after end")
}
v := r.data[r.idx]
r.idx++
return v
}
func (r *runeStream) AtEnd() bool {
return r.idx == len(r.data)
}
func (r *runeStream) String() string {
return string(r.data)
}
type pathParser struct {
p *runeStream
rxBuf bytes.Buffer
pBuf bytes.Buffer
simple bool // Contains no regexp expressions
}
func (p *pathParser) Parse(pattern string, strict, prefix bool) (*path, error) {
p.Reset()
p.p = &runeStream{data: []rune(pattern)}
var paramNames []string
// Write start.
p.rxBuf.WriteByte('^')
// Check correct start.
if len(pattern) == 0 {
return nil, fmt.Errorf("Paths must not be empty")
}
slash := p.p.Next()
if slash != '/' {
return nil, p.p.Err("paths must start with '/'")
}
p.startPart(slash)
// Iterate over runes.
for !p.p.AtEnd() {
r := p.p.Next()
var err error
switch r {
case '/':
p.startPart(r)
case '*':
p.wildcard()
case '(':
err = p.group()
case ')':
err = p.p.Err("unmatched ')'")
case '?':
p.simple = false
p.flushPart()
_, err = p.rxBuf.WriteRune(r)
case ':':
p.simple = false
var name string
name, err = p.param()
if err != nil {
break
}
paramNames = append(paramNames, name)
default:
_, err = p.pBuf.WriteRune(r)
}
if err != nil {
return nil, err
}
}
// Flush the last part
p.flushPart()
// Check all matcher
if p.rxBuf.String() == "^/(.*)" {
return &path{matcher: &allMatcher{}}, nil
}
if p.simple {
if prefix {
return &path{matcher: &stringPrefixMatcher{p.p.String()}}, nil
}
return &path{matcher: &stringMatcher{p.p.String(), strict}}, nil
}
if !strict && !prefix {
if p.rxBuf.Bytes()[p.rxBuf.Len()-1] != '/' {
p.rxBuf.WriteByte('/')
}
p.rxBuf.WriteByte('?')
}
if !prefix {
p.rxBuf.WriteByte('$')
}
regexpPattern, err := regexp.Compile(p.rxBuf.String())
if err != nil {
return nil, err
}
return &path{®expMatcher{regexpPattern}, regexpPattern, paramNames}, nil
}
func (p *pathParser) Reset() {
p.rxBuf.Reset()
p.pBuf.Reset()
p.simple = true
}
func (p *pathParser) flushPart() {
if p.pBuf.Len() == 0 {
return
}
safePattern := regexp.QuoteMeta(p.pBuf.String())
p.rxBuf.WriteString(safePattern)
p.pBuf.Reset()
}
func (p *pathParser) startPart(r rune) {
p.flushPart()
p.pBuf.WriteRune(r)
}
func (p *pathParser) wildcard() {
p.flushPart()
p.simple = false
p.rxBuf.WriteString("(.*)")
}
func (p *pathParser) group() error {
// Flush, if in the middle of something.
if p.pBuf.Len() > 1 {
p.flushPart()
}
// Walk over runes until end or until the group is complete.
quote := true
level := 1
Loop:
for !p.p.AtEnd() {
r := p.p.Next()
switch {
case r == '(':
// Increase group level
level++
case r == ')':
// Decrease group level
level--
case r == ':' || r == '/':
p.p.Back()
break Loop
case r == '?':
// Still quote, group incomplete
if level == 0 {
quote = false
}
break Loop
default:
// Copy runes until the closing brace is found.
p.pBuf.WriteRune(r)
}
}
part := p.pBuf.String()
if quote {
part = fmt.Sprintf("(%s)", part)
part = regexp.QuoteMeta(part)
} else {
part = fmt.Sprintf("(%s)?", regexp.QuoteMeta(part))
p.simple = false
}
p.rxBuf.WriteString(part)
p.pBuf.Reset()
return nil
}
func (p *pathParser) param() (string, error) {
var name bytes.Buffer
var pattern bytes.Buffer
Loop:
for !p.p.AtEnd() {
r := p.p.Next()
switch {
case isAlphaNumDash(r):
name.WriteRune(r)
case r == '(':
if name.Len() == 0 {
return "", p.p.Err("missing parameter name")
}
var err error
pattern, err = p.paramPattern()
if err != nil {
return "", err
}
break Loop
case r == ':' || r == '/':
p.p.Back()
break Loop
default:
return "", p.p.Err("invalid rune '" + string(r) + "'")
}
}
if pattern.Len() == 0 {
// Use the default pattern, which captures everything until
// the next '/'.
pattern.WriteString("[^/]+")
}
part := fmt.Sprintf("(?P<%s>%s)", name.String(), pattern.String())
p.flushPart()
p.rxBuf.WriteString(part)
return name.String(), nil
}
func (p *pathParser) paramPattern() (bytes.Buffer, error) {
var pattern bytes.Buffer
level := 1
Loop:
for !p.p.AtEnd() {
r := p.p.Next()
switch r {
case '(':
level++
case ')':
level--
if level > 0 {
break
}
// End found
break Loop
default:
pattern.WriteRune(r)
}
}
return pattern, nil
}
func parsePath(pattern string, strict, prefixOnly bool) (*path, error) {
parser := &pathParser{}
path, err := parser.Parse(pattern, strict, prefixOnly)
if err != nil {
return nil, err
}
return path, nil
}
func isAlphaNum(r rune) bool {
return unicode.In(r, unicode.Digit, unicode.Letter)
}
func isAlphaNumDash(r rune) bool {
return isAlphaNum(r) || r == '_' || r == '-'
}