-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutil.go
103 lines (88 loc) · 2.45 KB
/
util.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
// Copyright (c) Jeevanandam M. (https://github.com/jeevatkm)
// go-aah/router source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package router
import (
"fmt"
"path"
"strings"
)
const (
ruleStartByte = '['
ruleEndByte = ']'
)
func suffixCommaValue(s, v string) string {
if len(s) == 0 {
return v
}
return s + ", " + v
}
func findActionByHTTPMethod(method string) string {
if action, found := HTTPMethodActionMap[method]; found {
return action
}
return ""
}
func addRegisteredAction(methods map[string]map[string]uint8, route *Route) {
if target, found := methods[route.Target]; found {
target[route.Action] = 1
} else {
methods[route.Target] = map[string]uint8{route.Action: 1}
}
}
func routeConstraintExists(routePath string) bool {
sidx := strings.IndexByte(routePath, ruleStartByte)
eidx := strings.IndexByte(routePath, ruleEndByte)
return sidx > 0 || eidx > 0
}
// Return values are -
// 1. route path
// 2. route constraints
// 3. error
func parseRouteConstraints(routeName, routePath string) (string, map[string]string, error) {
if !routeConstraintExists(routePath) {
return routePath, nil, nil
}
constraints := make(map[string]string)
actualRoutePath := "/"
for _, seg := range strings.Split(routePath, "/")[1:] {
if seg[0] == paramByte || seg[0] == wildByte {
param, constraint, exists, valid := parameterConstraint(seg)
if exists {
if valid {
constraints[param[1:]] = constraint
} else {
return routePath, constraints, fmt.Errorf("'%s.path' has invalid contraint in path => '%s' (param => '%s')", routeName, routePath, seg)
}
}
actualRoutePath = path.Join(actualRoutePath, param)
} else {
actualRoutePath = path.Join(actualRoutePath, seg)
}
}
return actualRoutePath, constraints, nil
}
// Return values are -
// 1. path param
// 2. param constraint
// 3. is constraint exists
// 4. is constraint valid
func parameterConstraint(pathSeg string) (string, string, bool, bool) {
sidx := strings.IndexByte(pathSeg, ruleStartByte)
eidx := strings.IndexByte(pathSeg, ruleEndByte)
// Validation rule exists but invalid
if (sidx == -1 && eidx > 0) || (sidx >= 0 && eidx == -1) {
return "", "", true, false
}
constraint := strings.TrimSpace(pathSeg[sidx+1 : eidx])
return strings.TrimSpace(pathSeg[:sidx]),
constraint,
true,
len(constraint) > 0
}
func addSlashPrefix(v string) string {
if len(v) == 0 || v[0] == slashByte {
return v
}
return "/" + v
}