-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpath_parsed.go
40 lines (31 loc) · 975 Bytes
/
path_parsed.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
package openapi
import (
"fmt"
"regexp"
)
var reTemplateExpressions = regexp.MustCompile(`\{([^}]+)\}`)
// ParsedPath is a parsed URL path template.
type ParsedPath struct {
// Format string with the variables replaced with %s.
Format string
// VariableNames is the list of variable keys in order.
VariableNames []string
}
// Parse parses the path, returning a ParsedPath which includes a format specifier (see [fmt]) and a list of all variable names in order.
func (path Path) Parse() ParsedPath {
p := ParsedPath{}
// Find all variables in the url
p.Format = reTemplateExpressions.ReplaceAllStringFunc(string(path), func(s string) string {
// store the variable name
p.VariableNames = append(p.VariableNames, s[1:len(s)-1])
return "%s"
})
return p
}
func (p ParsedPath) String() string {
vars := make([]any, len(p.VariableNames))
for i, v := range p.VariableNames {
vars[i] = fmt.Sprintf("{%s}", v)
}
return fmt.Sprintf(p.Format, vars...)
}