This repository has been archived by the owner on Jun 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmatcher.go
267 lines (240 loc) · 7.13 KB
/
matcher.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
// Goro
//
// Created by Yakka
// http://theyakka.com
//
// Copyright (c) 2019 Yakka LLC.
// All rights reserved.
// See the LICENSE file for licensing details and requirements.
package goro
import (
"fmt"
"net/http"
"strings"
"time"
)
// Matcher is the global matching engine
type Matcher struct {
router *Router
LogMatchTime bool
FallbackToCatchAll bool
}
// Match represents a matched node in the tree
type Match struct {
Node *Node
Params map[string][]string
CatchAllValue string
ParentMatch *Match
}
// NewMatch creates a new Match instance
func NewMatch(node *Node) *Match {
return &Match{
Node: node,
Params: map[string][]string{},
CatchAllValue: "",
}
}
// NewMatchWithParent creates a new instance of a match that passes down the values from
// the parent match
func NewMatchWithParent(node *Node, parentMatch *Match) *Match {
match := &Match{
Node: node,
Params: map[string][]string{},
CatchAllValue: "",
}
match.ParentMatch = parentMatch
if parentMatch != nil {
match.Params = map[string][]string{}
// need to copy
for key, value := range parentMatch.Params {
match.Params[key] = value
}
match.CatchAllValue = parentMatch.CatchAllValue
}
return match
}
func (match *Match) String() string {
return fmt.Sprintf("goro.Match # part=%s, wc=%v, ca=%v",
match.Node.part, match.Params, match.CatchAllValue)
}
// NewMatcher creates a new instance of the Matcher
func NewMatcher(router *Router) *Matcher {
return &Matcher{
router: router,
LogMatchTime: false,
FallbackToCatchAll: true,
}
}
// MatchPathToRoute attempts to match the given path to a registered Route
func (m *Matcher) MatchPathToRoute(method string, path string, req *http.Request) *Match {
startTime := time.Now()
tree := m.router.routes
if tree == nil {
return nil // no routes registered for this method
}
nodesToCheck := tree.nodes
var currentMatches []*Match
candidate := NewMatchCandidate(path)
if path == RootPath {
candidate.part = RootPath
}
finalMatches := []*Match{}
catchAlls := []*Match{}
// loop until no more match candidates
for candidate != NoMatchCandidate() {
var matches []*Match
var catchAllMatches []*Match
if currentMatches == nil {
matches, catchAllMatches, _ = m.matchNodesForCandidate(method, candidate, nodesToCheck)
// Log("++", candidate.part)
// Log("++", matches, catchAllMatches)
} else {
matches, catchAllMatches, _ = m.matchCurrentMatchesForCandidate(method, candidate, currentMatches)
// Log("--", candidate.part)
// Log("--", matches)
}
if len(catchAllMatches) > 0 {
// append the old catch alls to the new ones so the deeper matches take precedent
catchAlls = append(catchAllMatches, catchAlls...)
}
if len(matches) == 0 {
break
}
currentMatches = matches
if !candidate.HasRemainingCandidates() {
finalMatches = append(finalMatches, matches...)
break
} else {
candidate = candidate.NextCandidate()
}
}
// fmt.Println("")
// fmt.Println("")
// Log("-----")
// Log("final matches: ", finalMatches)
// Log("catch alls: ", catchAlls)
var matchToUse *Match
if len(finalMatches) > 0 {
if !m.FallbackToCatchAll {
matchToUse = finalMatches[0]
} else {
// check to see if the match contains a route that matches the requested method.
// if not, fallback to a catch-all route (if one is matched)
for _, match := range finalMatches {
if match.Node.RouteForMethod(method) != nil {
matchToUse = match
break
}
}
}
}
if matchToUse == nil && len(catchAlls) > 0 {
matchToUse = catchAlls[0]
}
// fmt.Println("")
// Log("-----")
// Log("final match: ", matchToUse)
if m.LogMatchTime {
endTime := time.Now()
Log("Matched in", endTime.Sub(startTime))
}
return matchToUse
}
func (m *Matcher) matchNodesForCandidate(method string, candidate MatchCandidate, nodes []*Node) (matches []*Match, catchalls []*Match, errorCode int) {
if candidate != NoMatchCandidate() {
return m.checkNodesForMatches(method, candidate, nodes, nil)
}
return []*Match{}, []*Match{}, 0
}
func (m *Matcher) matchCurrentMatchesForCandidate(method string, candidate MatchCandidate, currentMatches []*Match) (matches []*Match, catchalls []*Match, errorCode int) {
matchedNodes := []*Match{}
catchAllNodes := []*Match{}
errCode := 0
for _, match := range currentMatches {
node := match.Node
if node.HasChildren() {
nodeMatches, nodeCatchAlls, matchErrCode := m.checkNodesForMatches(method, candidate, node.nodes, match)
matchedNodes = append(matchedNodes, nodeMatches...)
catchAllNodes = append(catchAllNodes, nodeCatchAlls...)
if errCode != 0 {
errCode = matchErrCode
}
}
}
return matchedNodes, catchAllNodes, errCode
}
func (m *Matcher) checkNodesForMatches(method string, candidate MatchCandidate, nodes []*Node, parentMatch *Match) (matches []*Match, catchalls []*Match, errorCode int) {
matchedNodes := []*Match{}
catchAllNodes := []*Match{}
errCode := 0
for _, node := range nodes {
isWildcard := isWildcardPart(node.part)
if (node.nodeType == ComponentTypeFixed && strings.ToLower(node.part) == strings.ToLower(candidate.part)) ||
isWildcard {
match := NewMatchWithParent(node, parentMatch)
if isWildcard {
paramKey := strings.ToLower(node.part[1:len(node.part)])
arr := match.Params[paramKey]
if arr == nil {
arr = []string{}
}
arr = append(arr, candidate.part)
match.Params[paramKey] = arr
}
matchedNodes = append(matchedNodes, match)
if m.FallbackToCatchAll == false && candidate.HasRemainingCandidates() == false {
break // break early, we found a match
}
} else if isCatchAllPart(node.part) {
match := NewMatchWithParent(node, parentMatch)
match.CatchAllValue = candidate.currentPath
catchAllNodes = append(catchAllNodes, match)
}
}
return matchedNodes, catchAllNodes, errCode
}
// MatchCandidate is a helper class for matching path components
type MatchCandidate struct {
part string
remainder string
currentPath string
}
// NewMatchCandidate creates a new match candidate instance and initializes if for the first part
func NewMatchCandidate(path string) MatchCandidate {
cleanPath := path
if strings.HasPrefix(path, "/") {
cleanPath = path[1:len(path)]
}
split := strings.SplitN(cleanPath, "/", 2)
candidate := MatchCandidate{
part: split[0],
remainder: "",
currentPath: cleanPath,
}
if len(split) == 2 {
candidate.remainder = split[1]
}
return candidate
}
// NextCandidate returns the next MatchCandidate in the full path
func (mc MatchCandidate) NextCandidate() MatchCandidate {
if mc.remainder == "" {
return NoMatchCandidate()
}
return NewMatchCandidate(mc.remainder)
}
// HasRemainingCandidates returns true if the MatchCandidate has more candidate parts
func (mc MatchCandidate) HasRemainingCandidates() bool {
return mc.remainder != ""
}
// NoMatchCandidate represents an empty MatchCandidate
func NoMatchCandidate() MatchCandidate {
return MatchCandidate{
part: "",
remainder: "",
}
}
// IsNoMatch returns true if the MatchCandidate equals the NoMatchCandidate value
func (mc MatchCandidate) IsNoMatch() bool {
return mc == NoMatchCandidate()
}