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
|
package growel
import (
"strings"
)
func NewRouter() *Router {
return &Router{}
}
// Router.Add adds a route with specified method, path and handler
// it splits path into segments for matching
func (r *Router) Add(method string, path string, h Handler) {
parts := splitPath(path)
r.routes = append(r.routes, Route{method, parts, h})
}
// Router.Find finds route with same HTTP method and path
// returns the handler and dynamic parameters
//
// handler is a function that wraps Context
// params is a map of parameters from dynamic routing
func (r *Router) Find(method string, path string) (
handler Handler, params map[string]string) {
parts := splitPath(path)
for _, rt := range r.routes {
// match HTTP method
if rt.method != method {
continue
}
// match path part number
if len(rt.parts) != len(parts) {
continue
}
// compare each segment
params := make(map[string]string)
matched := true
for i, seg := range rt.parts {
// parse dynamic parameter
if strings.HasPrefix(seg, ":") {
params[seg[1:]] = parts[i]
continue
}
// static mismatch
if seg != parts[i] {
matched = false
break
}
}
if matched {
return rt.handler, params
}
}
return nil, nil
}
/* === helpers === */
// splitPath splits path into segments for matching
func splitPath(path string) []string {
return strings.Split(strings.Trim(path, "/"), "/")
}
|