-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwildcard.go
More file actions
70 lines (60 loc) · 1.43 KB
/
wildcard.go
File metadata and controls
70 lines (60 loc) · 1.43 KB
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
package httpx
import "strings"
// FixWildcardPathIfNeed normalizes wildcard path syntax based on router capability.
//
// It returns:
// - path: the path to register
// - param: the wildcard param key to read from Context.Param
//
// Rules:
// - If path has no wildcard, param is "" and path is returned unchanged.
// - If router supports named wildcards, path is returned unchanged and param is wildcard name.
// - If router does not support named wildcards, named wildcard segments are rewritten to "*"
// and param is "*".
func FixWildcardPathIfNeed(r RouterFeatureProvider, path string) (fixedPath string, param string) {
param = wildcardParamName(path)
if param == "" {
return path, ""
}
if r.SupportsRouterFeature(RouterFeatureNamedWildcard) {
return path, param
}
return toAnonymousWildcardPath(path), "*"
}
func toAnonymousWildcardPath(path string) string {
if path == "" {
return path
}
var b strings.Builder
b.Grow(len(path))
for i := 0; i < len(path); {
if path[i] != '*' {
b.WriteByte(path[i])
i++
continue
}
b.WriteByte('*')
i++
for i < len(path) && path[i] != '/' {
i++
}
}
return b.String()
}
func wildcardParamName(path string) string {
for i := 0; i < len(path); i++ {
if path[i] != '*' {
continue
}
start := i + 1
end := start
for end < len(path) && path[end] != '/' {
end++
}
if start == end {
return "*"
}
return path[start:end]
}
return ""
}