@@ -7,6 +7,31 @@ import (
7
7
"strings"
8
8
)
9
9
10
+ // GetRegexForPath returns a compiled regular expression for the given path template.
11
+ //
12
+ // This function takes a path template string `tpl` and generates a regular expression
13
+ // that matches the structure of the template. The template can include placeholders
14
+ // enclosed in braces `{}` with optional custom patterns.
15
+ //
16
+ // Placeholders in the template can be defined as:
17
+ // - `{name}`: Matches any sequence of characters except '/'
18
+ // - `{name:pattern}`: Matches the specified custom pattern
19
+ //
20
+ // The function ensures that the template is well-formed, with balanced and properly
21
+ // nested braces. If the template is invalid, an error is returned.
22
+ //
23
+ // Parameters:
24
+ // - tpl: The path template string to convert into a regular expression.
25
+ //
26
+ // Returns:
27
+ // - *regexp.Regexp: A compiled regular expression that matches the template.
28
+ // - error: An error if the template is invalid or the regular expression cannot be compiled.
29
+ //
30
+ // Example:
31
+ //
32
+ // regex, err := GetRegexForPath("/orders/{id:[0-9]+}/items/{itemId}")
33
+ // // regex: ^/orders/([0-9]+)/items/([^/]+)$
34
+ // // err: nil
10
35
func GetRegexForPath (tpl string ) (* regexp.Regexp , error ) {
11
36
// Check if it is well-formed.
12
37
idxs , errBraces := BraceIndices (tpl )
@@ -69,6 +94,27 @@ func GetRegexForPath(tpl string) (*regexp.Regexp, error) {
69
94
return reg , nil
70
95
}
71
96
97
+ // BraceIndices returns the indices of the opening and closing braces in a string.
98
+ //
99
+ // It scans the input string `s` and identifies the positions of matching pairs
100
+ // of braces ('{' and '}'). The function ensures that the braces are balanced
101
+ // and properly nested.
102
+ //
103
+ // If the braces are unbalanced or improperly nested, an error is returned.
104
+ //
105
+ // Parameters:
106
+ // - s: The input string to scan for braces.
107
+ //
108
+ // Returns:
109
+ // - []int: A slice of integers where each pair of indices represents the
110
+ // start and end positions of a matching pair of braces.
111
+ // - error: An error if the braces are unbalanced or improperly nested.
112
+ //
113
+ // Example:
114
+ //
115
+ // indices, err := BraceIndices("/orders/{id}/items/{itemId}")
116
+ // // indices: [8, 12, 19, 26]
117
+ // // err: nil
72
118
func BraceIndices (s string ) ([]int , error ) {
73
119
var level , idx int
74
120
var idxs []int
0 commit comments