-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute.go
95 lines (81 loc) · 2.16 KB
/
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
package dynamic_proxy
import (
"regexp"
"strings"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/lemon-1997/dynamic-proxy/httprule"
)
var encodedPathSplitter = regexp.MustCompile("(/|%2F)")
type Router interface {
Add(method, path string, extra interface{}) error
Match(method, path string) (map[string]string, interface{}, bool)
}
type Pattern struct {
runtime.Pattern
extra interface{}
}
type httpRouter struct {
unescapeMode runtime.UnescapingMode
patterns map[string][]Pattern
}
func NewRouter() Router {
return &httpRouter{
unescapeMode: runtime.UnescapingModeDefault,
patterns: make(map[string][]Pattern),
}
}
func (r *httpRouter) Add(method, path string, extra interface{}) error {
c, err := httprule.Parse(path)
if err != nil {
return err
}
tmpl := c.Compile()
p, err := runtime.NewPattern(tmpl.Version, tmpl.OpCodes, tmpl.Pool, tmpl.Verb)
if err != nil {
return err
}
r.patterns[method] = append(r.patterns[method], Pattern{
Pattern: p,
extra: extra,
})
return nil
}
func (r *httpRouter) Match(method, path string) (map[string]string, interface{}, bool) {
if r == nil {
return nil, nil, false
}
if !strings.HasPrefix(path, "/") {
return nil, nil, false
}
var pathComponents []string
pathComponents = strings.Split(path[1:], "/")
if r.unescapeMode == runtime.UnescapingModeAllCharacters {
pathComponents = encodedPathSplitter.Split(path[1:], -1)
} else {
pathComponents = strings.Split(path[1:], "/")
}
lastPathComponent := pathComponents[len(pathComponents)-1]
patterns := r.patterns[method]
for _, item := range patterns {
var verb string
patVerb := item.Verb()
idx := -1
if patVerb != "" && strings.HasSuffix(lastPathComponent, ":"+patVerb) {
idx = len(lastPathComponent) - len(patVerb) - 1
}
if idx == 0 {
return nil, nil, false
}
comps := make([]string, len(pathComponents))
copy(comps, pathComponents)
if idx > 0 {
comps[len(comps)-1], verb = lastPathComponent[:idx], lastPathComponent[idx+1:]
}
pathParams, err := item.MatchAndEscape(comps, verb, r.unescapeMode)
if err != nil {
continue
}
return pathParams, item.extra, true
}
return nil, nil, false
}