forked from metaverse/truss
/
embeddable_funcs.go
71 lines (62 loc) · 2.18 KB
/
embeddable_funcs.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
package httptransport
import (
"fmt"
"strings"
)
// Contains all the functions which must be used within templates. Stored all
// together in this file, the string form of their source code can be extracted
// with the function `AllFuncSourceCode`. All these functions are kept here so
// they can be properly tested, while still allowing them to be conveniently
// templated into the code.
// PathParams takes a url and a gRPC-annotation style url template, and
// returns a map of the named parameters in the template and their values in
// the given url.
//
// PathParams does not support the entirety of the URL template syntax defined
// in third_party/googleapis/google/api/httprule.proto. Only a small subset of
// the functionality defined there is implemented here.
func PathParams(url string, urlTmpl string) (map[string]string, error) {
rv := map[string]string{}
pmp := BuildParamMap(urlTmpl)
expectedLen := len(strings.Split(strings.TrimRight(urlTmpl, "/"), "/"))
recievedLen := len(strings.Split(strings.TrimRight(url, "/"), "/"))
if expectedLen != recievedLen {
return nil, fmt.Errorf("expecting a path containing %d parts, provided path contains %d parts", expectedLen, recievedLen)
}
parts := strings.Split(url, "/")
for k, v := range pmp {
rv[k] = parts[v]
}
return rv, nil
}
// BuildParamMap takes a string representing a url template and returns a map
// indicating the location of each parameter within that url, where the
// location is the index as if in a slash-separated sequence of path
// components. For example, given the url template:
//
// "/v1/{a}/{b}"
//
// The returned param map would look like:
//
// map[string]int {
// "a": 2,
// "b": 3,
// }
func BuildParamMap(urlTmpl string) map[string]int {
rv := map[string]int{}
parts := strings.Split(urlTmpl, "/")
for idx, part := range parts {
if strings.ContainsAny(part, "{}") {
param := RemoveBraces(part)
rv[param] = idx
}
}
return rv
}
// RemoveBraces replace all curly braces in the provided string, opening and
// closing, with empty strings.
func RemoveBraces(val string) string {
val = strings.Replace(val, "{", "", -1)
val = strings.Replace(val, "}", "", -1)
return val
}