-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathtemplate.go
88 lines (77 loc) · 2.39 KB
/
template.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
package deeplinks
import (
"fmt"
"strings"
)
// matchPath extracting path variables with template.
// it returns nil, false, if path doesn't match template
// got example: matchPath("/joinchat/{chat_id}", "/joinchat/abcdefg") returns {"chat_id":"abcdefg"}, false
// spiced up implementaition from https://git.io/Jtcv0 (cuz why not?)
func matchPath(tpl, path string) (map[string]string, bool) {
//? if template doesn't have pattern
if !strings.ContainsAny(tpl, "{}") {
if tpl == path {
return map[string]string{}, true
}
return nil, false
}
//? if template or path are not global filepath
if !strings.HasPrefix(tpl, "/") || !strings.HasPrefix(path, "/") {
return nil, false
}
tplPathItems := strings.Split(tpl, "/")
pathItems := strings.Split(path, "/")
if len(tplPathItems) != len(pathItems) {
return nil, false
}
res := make(map[string]string)
for i, tplPathItem := range tplPathItems {
//? if this item not a variable, we just need to check it but don't extract
if !strings.HasPrefix(tplPathItem, "{") || !strings.HasSuffix(tplPathItem, "}") {
if tplPathItem != pathItems[i] {
return nil, false
}
continue
}
//? {chat_id} -> chat_id
templateObject := stringsTrimSuffixPrefix("{", tplPathItem, "}")
// TODO: decide, do we REALLY need check patterns?
//if !stringsContainsOnlyFunc(templateObject, validIdentRunes) {
// panic("got invalid template") // panicing, cause we must check templates BEFORE it's usage
//}
res[templateObject] = pathItems[i]
}
return res, true
}
func fillTemplate(tpl string, data map[string]string) (string, error) {
//? if template doesn't have pattern
if !strings.ContainsAny(tpl, "{}") {
if len(data) > 0 {
return "", fmt.Errorf("unused keys: [%v]", strings.Join(stringStringMapKeys(data), ", "))
}
return tpl, nil
}
var isAbstract bool
//? if template or path are not global filepath
if !strings.HasPrefix(tpl, "/") {
isAbstract = true
}
tplPathItems := strings.Split(tpl, "/")
for i, tplPathItem := range tplPathItems {
if !strings.HasPrefix(tplPathItem, "{") || !strings.HasSuffix(tplPathItem, "}") {
continue
}
//? {chat_id} -> chat_id
dataKey := stringsTrimSuffixPrefix("{", tplPathItem, "}")
v, ok := data[dataKey]
if !ok {
return "", fmt.Errorf("key '%v' not found", dataKey)
}
tplPathItems[i] = v
}
res := strings.Join(tplPathItems, "/")
if !isAbstract {
res = "/" + res
}
return res, nil
}