-
Notifications
You must be signed in to change notification settings - Fork 34
/
util_path_pattern.go
93 lines (75 loc) · 1.72 KB
/
util_path_pattern.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
package transformer
import (
"strings"
"github.com/julienschmidt/httprouter"
"github.com/pkg/errors"
)
func ParamsFromMap(m map[string]string) httprouter.Params {
params := httprouter.Params{}
for k, v := range m {
params = append(params, httprouter.Param{
Key: k,
Value: v,
})
}
return params
}
func NewPathnamePattern(pattern string) *PathnamePattern {
parts := ToPathParts(pattern)
idxKeys := map[int]string{}
for i, p := range parts {
if p[0] == ':' {
idxKeys[i] = p[1:]
}
}
return &PathnamePattern{
parts,
idxKeys,
}
}
type PathnamePattern struct {
parts []string
idxKeys map[int]string
}
func (pp *PathnamePattern) String() string { return "/" + strings.Join(pp.parts, "/") }
func (pp *PathnamePattern) Stringify(params httprouter.Params) string {
if len(pp.idxKeys) == 0 {
return pp.String()
}
parts := append([]string{}, pp.parts...)
for idx, key := range pp.idxKeys {
v := params.ByName(key)
if v == "" {
v = "-"
}
parts[idx] = v
}
return (&PathnamePattern{parts: parts}).String()
}
func (pp *PathnamePattern) Parse(pathname string) (params httprouter.Params, err error) {
parts := ToPathParts(pathname)
if len(parts) != len(pp.parts) {
return nil, errors.Errorf("pathname %s is not match %s", pathname, pp)
}
for idx, part := range pp.parts {
if key, ok := pp.idxKeys[idx]; ok {
params = append(params, httprouter.Param{
Key: key,
Value: parts[idx],
})
} else if part != parts[idx] {
return nil, errors.Errorf("pathname %s is not match %s", pathname, pp)
}
}
return
}
func ToPathParts(p string) []string {
p = httprouter.CleanPath(p)
if p[0] == '/' {
p = p[1:]
}
if p == "" {
return make([]string, 0)
}
return strings.Split(p, "/")
}