-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathroute.go
69 lines (57 loc) · 1.27 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
package climux
import (
"fmt"
"strings"
)
// Route holds the information to match against Requests
type Route struct {
handler Handler
path string
description string
}
func (r Route) String() string {
if r.description == "" {
return fmt.Sprintf(" %s", r.path)
}
return fmt.Sprintf(" %s: %s", r.path, r.description)
}
func isRequiredParameter(s string) bool {
return s[:1] == "{" && s[len(s)-1:] == "}"
}
func isOptionalParameter(s string) bool {
return s[:1] == "[" && s[len(s)-1:] == "]"
}
func isParameter(s string) bool {
return isRequiredParameter(s) || isOptionalParameter(s)
}
func (r *Route) getVars(req *Request) map[string]string {
vars := map[string]string{}
pathArgs := strings.Split(r.path, " ")
for i, arg := range req.args {
if isParameter(pathArgs[i]) {
key := pathArgs[i][1 : len(pathArgs[i])-1]
vars[key] = arg
}
}
return vars
}
func (r *Route) match(req *Request) bool {
pathArgs := strings.Split(r.path, " ")
if len(req.args) > len(pathArgs) {
return false
}
for i := 0; i < len(pathArgs); i++ {
if i >= len(req.args) {
if !isOptionalParameter(pathArgs[i]) {
return false
}
} else {
if !isParameter(pathArgs[i]) {
if req.args[i] != pathArgs[i] {
return false
}
}
}
}
return true
}