-
Notifications
You must be signed in to change notification settings - Fork 13
/
route.go
345 lines (288 loc) · 7.49 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
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
package mux
import (
"fmt"
"net/http"
"strings"
)
const (
kindNormalPath = iota
kindVarsPath
kindRegexPath
)
// RouteInterface that you can create your own custom route
type RouteInterface interface {
HasVars() bool
HasError() bool
SetError(error)
GetError() error
HasHandler() bool
GetHandler() http.Handler
Handler(http.Handler)
SetMethodName(string)
GetMethodName() string
ExtractVars(req *http.Request) Vars
GetPath() string
Path(string) RouteInterface
HandlerFunc(handler func(http.ResponseWriter, *http.Request)) RouteInterface
GetMatchers() Matchers
Kind() int
Match(req *http.Request) RouteInterface
}
// Route stores information to match a request and build URLs.
type Route struct {
// kind of route (regex, vars or normal)
kind int
// Request handler for the route.
handler http.Handler
// List of Matchers.
ms Matchers
// The name used to build URLs.
name string
// Error resulted from building a route.
err error
// MethodName used to build proper error messages
methodName string
// path used to build proper error messages
path string
// varIndexies used to extract vars
varIndexies map[string]int
router *Router
}
// NewRoute returns a new route instance.
func NewRoute(router *Router) RouteInterface {
return &Route{
router: router,
ms: Matchers([]Matcher{}),
varIndexies: make(map[string]int),
}
}
// Match matches the route against the request.
// if match is successfully then return route else return nil
func (r *Route) Match(req *http.Request) RouteInterface {
if r.err != nil {
return nil
}
// Match everything.
for _, m := range r.ms {
if matched := m.Match(req); !matched {
return nil
}
}
return r
}
// HasHandler returns ture if route has a handler.
func (r *Route) HasHandler() bool {
return r.handler != nil
}
// GetHandler returns the handler for the route, if any.
func (r *Route) GetHandler() http.Handler {
return r.handler
}
// Handler sets a handler for the route.
func (r *Route) Handler(h http.Handler) {
if r.err == nil {
r.handler = h
}
}
// HasError check if an error exists.
func (r *Route) HasError() bool {
return r.err != nil
}
// GetError returns an error resulted from building the route
func (r *Route) GetError() error {
return r.err
}
// SetError set an error (Resulted from building).
func (r *Route) SetError(err error) {
r.err = err
}
//SetMethodName set the method name for the route
func (r *Route) SetMethodName(m string) {
r.methodName = m
}
// GetMethodName get the method name for the route
func (r *Route) GetMethodName() string {
return r.methodName
}
// GetMatchers get the Matchers for the route
func (r *Route) GetMatchers() Matchers {
return r.ms
}
// HandlerFunc sets a handler function for the route.
func (r *Route) HandlerFunc(handler func(http.ResponseWriter, *http.Request)) RouteInterface {
r.Handler(http.HandlerFunc(handler))
return r
}
// Name sets the name for the route, used to build URLs.
func (r *Route) Name(name string) *Route {
if r.name != "" {
r.err = NewBadRouteError(r, fmt.Sprintf("route already has name %q, can't set %q", r.name, name))
return r
}
if r.err == nil {
r.name = name
}
return r
}
// GetName returns the name for the route.
func (r *Route) GetName() string {
return r.name
}
// addMatcher adds a matcher to the route.
func (r *Route) addMatcher(m Matcher) RouteInterface {
if r.err == nil {
r.ms = append(r.ms, m)
}
return r
}
// Path adds a matcher for the URL path.
// It accepts a path with zero variables. The
// template must start with a "/".
// For example:
//
// r := mux.Classic()
// r.Path("/billing/").Handler(BillingHandler)
// r.Path("/user/:number/comment/:string").Handler(commentHandler)
// r.Path("/article/#([a-z]{,10})").Handler(articleHandler)
//
func (r *Route) Path(path string) RouteInterface {
if r.path != "" {
r.err = NewBadRouteError(r, fmt.Sprintf("route already has path can't set a new path %v", path))
}
var matcher Matcher
switch {
case containsRegex(path):
matcher = newPathRegexMatcher(path)
r.extractVarsIndexies("#", path, "var")
r.kind = kindRegexPath
case containsVars(path):
matcher = newPathWithVarsMatcher(path)
r.extractVarsIndexies(":", path, "")
r.kind = kindVarsPath
default:
matcher = pathMatcher(path)
r.kind = kindNormalPath
}
r.path = path
r.addMatcher(matcher)
return r
}
//GetPath returns the handler for the route.
func (r *Route) GetPath() string {
return r.path
}
func (r *Route) extractVarsIndexies(prefix string, path string, name string) {
urlSeg := strings.Split(path, "/")
indexies := map[string]int{}
var count int
for k, v := range urlSeg {
if strings.HasPrefix(v, prefix) {
if name != "" {
v = name
}
if _, found := indexies[v]; !found {
indexies[v] = k
continue
}
count++
indexies[v+string(count)] = k
}
}
r.varIndexies = indexies
}
//HasVars check if path has any vars
func (r *Route) HasVars() bool {
return len(r.varIndexies) != 0
}
type Vars map[string]string
// Get return the key value, of the current *http.Request queries
func (v Vars) Get(key string) string {
if value, found := v[key]; found {
return value
}
return ""
}
// GetAll returns all queries of the current *http.Request queries
func (v Vars) GetAll() map[string]string {
return v
}
//ExtractVars extract all vars of the current path
func (r *Route) ExtractVars(req *http.Request) Vars {
urlSeg := strings.Split(req.URL.Path, "/")
vars := Vars(map[string]string{})
for k, v := range r.varIndexies {
vars[k] = urlSeg[v]
}
return vars
}
// Schemes adds a matcher for URL schemes.
// It accepts a sequence of schemes to be matched, e.g.: "http", "https".
func (r *Route) Schemes(schemes ...string) RouteInterface {
return r.addMatcher(newSchemeMatcher(schemes...))
}
// Headers adds a matcher for request header values.
// It accepts a sequence of key/value pairs to be matched. For example:
//
// For example:
//
// r := mux.Classic()
// r.Headers("Content-Type", "application/json", "X-Requested-With", "XMLHttpRequest")
//
// Invaild example:
//
// r := mux.Classic()
// r.Headers("Content-Type")
//
//
// The first example will only match if both request header values match.
// the second example will never match because the count of key/value is odd.
//
// If one of the value is an empty string, it will match any value if the key is set.
func (r *Route) Headers(pairs ...string) RouteInterface {
if r.err != nil {
return r
}
matcher, err := newHeaderMatcher(pairs...)
if err != nil {
r.err = err
}
r.addMatcher(matcher)
return r
}
// HeadersRegex adds a matcher for request header values.
// It accepts a sequence of key/value pairs to be matched. For example:
//
// For example:
//
// r := mux.Classic()
// r.Headers("Content-Type", "application/(json|html)")
//
// Invaild example:
//
// r := mux.Classic()
// r.Headers("Content-Type")
//
//
// The first example will only match if both request header values match.
// the second example will never match because the count of key/value is odd.
//
// If one of the value is an empty string, it will match any value if the key is set.
func (r *Route) HeadersRegex(pairs ...string) RouteInterface {
if r.err != nil {
return r
}
matcher, err := newHeaderRegexMatcher(pairs...)
if err != nil {
r.err = err
}
r.addMatcher(matcher)
return r
}
// MatcherFunc adds a custom function to be used as request matcher.
func (r *Route) MatcherFunc(f MatcherFunc) RouteInterface {
return r.addMatcher(f)
}
//Kind returns kind of route
func (r *Route) Kind() int {
return r.kind
}