MCPcopy
hub / github.com/gorilla/mux / newRouteRegexp

Function newRouteRegexp

regexp.go:41–150  ·  view source on GitHub ↗

newRouteRegexp parses a route template and returns a routeRegexp, used to match a host, a path or a query string. It will extract named variables, assemble a regexp to be matched, create a "reverse" template to build URLs and compile regexps to validate variable values used in URL building. Previo

(tpl string, typ regexpType, options routeRegexpOptions)

Source from the content-addressed store, hash-verified

39// names ([a-zA-Z_][a-zA-Z0-9_]*), but currently the only restriction is that
40// name and pattern can't be empty, and names can't contain a colon.
41func newRouteRegexp(tpl string, typ regexpType, options routeRegexpOptions) (*routeRegexp, error) {
42 // Check if it is well-formed.
43 idxs, errBraces := braceIndices(tpl)
44 if errBraces != nil {
45 return nil, errBraces
46 }
47 // Backup the original.
48 template := tpl
49 // Now let's parse it.
50 defaultPattern := "[^/]+"
51 if typ == regexpTypeQuery {
52 defaultPattern = ".*"
53 } else if typ == regexpTypeHost {
54 defaultPattern = "[^.]+"
55 }
56 // Only match strict slash if not matching
57 if typ != regexpTypePath {
58 options.strictSlash = false
59 }
60 // Set a flag for strictSlash.
61 endSlash := false
62 if options.strictSlash && strings.HasSuffix(tpl, "/") {
63 tpl = tpl[:len(tpl)-1]
64 endSlash = true
65 }
66 varsN := make([]string, len(idxs)/2)
67 varsR := make([]*regexp.Regexp, len(idxs)/2)
68 pattern := bytes.NewBufferString("")
69 pattern.WriteByte('^')
70 reverse := bytes.NewBufferString("")
71 var end int
72 var err error
73 for i := 0; i < len(idxs); i += 2 {
74 // Set all values we are interested in.
75 raw := tpl[end:idxs[i]]
76 end = idxs[i+1]
77 parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2)
78 name := parts[0]
79 patt := defaultPattern
80 if len(parts) == 2 {
81 patt = parts[1]
82 }
83 // Name or pattern can't be empty.
84 if name == "" || patt == "" {
85 return nil, fmt.Errorf("mux: missing name or pattern in %q",
86 tpl[idxs[i]:end])
87 }
88 // Build the regexp pattern.
89 fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), varGroupName(i/2), patt)
90
91 // Build the reverse template.
92 fmt.Fprintf(reverse, "%s%%s", raw)
93
94 // Append variable name and compiled pattern.
95 varsN[i/2] = name
96 varsR[i/2], err = regexp.Compile(fmt.Sprintf("^%s$", patt))
97 if err != nil {
98 return nil, err

Callers 3

Test_copyRouteConfFunction · 0.85
addRegexpMatcherMethod · 0.85
TestNewRegexpFunction · 0.85

Calls 2

braceIndicesFunction · 0.85
varGroupNameFunction · 0.85

Tested by 2

Test_copyRouteConfFunction · 0.68
TestNewRegexpFunction · 0.68