You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

324 lines
8.7 KiB

  1. // Copyright 2012 The Gorilla Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package mux
  5. import (
  6. "bytes"
  7. "fmt"
  8. "net/http"
  9. "net/url"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. )
  14. // newRouteRegexp parses a route template and returns a routeRegexp,
  15. // used to match a host, a path or a query string.
  16. //
  17. // It will extract named variables, assemble a regexp to be matched, create
  18. // a "reverse" template to build URLs and compile regexps to validate variable
  19. // values used in URL building.
  20. //
  21. // Previously we accepted only Python-like identifiers for variable
  22. // names ([a-zA-Z_][a-zA-Z0-9_]*), but currently the only restriction is that
  23. // name and pattern can't be empty, and names can't contain a colon.
  24. func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash, useEncodedPath bool) (*routeRegexp, error) {
  25. // Check if it is well-formed.
  26. idxs, errBraces := braceIndices(tpl)
  27. if errBraces != nil {
  28. return nil, errBraces
  29. }
  30. // Backup the original.
  31. template := tpl
  32. // Now let's parse it.
  33. defaultPattern := "[^/]+"
  34. if matchQuery {
  35. defaultPattern = "[^?&]*"
  36. } else if matchHost {
  37. defaultPattern = "[^.]+"
  38. matchPrefix = false
  39. }
  40. // Only match strict slash if not matching
  41. if matchPrefix || matchHost || matchQuery {
  42. strictSlash = false
  43. }
  44. // Set a flag for strictSlash.
  45. endSlash := false
  46. if strictSlash && strings.HasSuffix(tpl, "/") {
  47. tpl = tpl[:len(tpl)-1]
  48. endSlash = true
  49. }
  50. varsN := make([]string, len(idxs)/2)
  51. varsR := make([]*regexp.Regexp, len(idxs)/2)
  52. pattern := bytes.NewBufferString("")
  53. pattern.WriteByte('^')
  54. reverse := bytes.NewBufferString("")
  55. var end int
  56. var err error
  57. for i := 0; i < len(idxs); i += 2 {
  58. // Set all values we are interested in.
  59. raw := tpl[end:idxs[i]]
  60. end = idxs[i+1]
  61. parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2)
  62. name := parts[0]
  63. patt := defaultPattern
  64. if len(parts) == 2 {
  65. patt = parts[1]
  66. }
  67. // Name or pattern can't be empty.
  68. if name == "" || patt == "" {
  69. return nil, fmt.Errorf("mux: missing name or pattern in %q",
  70. tpl[idxs[i]:end])
  71. }
  72. // Build the regexp pattern.
  73. fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), varGroupName(i/2), patt)
  74. // Build the reverse template.
  75. fmt.Fprintf(reverse, "%s%%s", raw)
  76. // Append variable name and compiled pattern.
  77. varsN[i/2] = name
  78. varsR[i/2], err = regexp.Compile(fmt.Sprintf("^%s$", patt))
  79. if err != nil {
  80. return nil, err
  81. }
  82. }
  83. // Add the remaining.
  84. raw := tpl[end:]
  85. pattern.WriteString(regexp.QuoteMeta(raw))
  86. if strictSlash {
  87. pattern.WriteString("[/]?")
  88. }
  89. if matchQuery {
  90. // Add the default pattern if the query value is empty
  91. if queryVal := strings.SplitN(template, "=", 2)[1]; queryVal == "" {
  92. pattern.WriteString(defaultPattern)
  93. }
  94. }
  95. if !matchPrefix {
  96. pattern.WriteByte('$')
  97. }
  98. reverse.WriteString(raw)
  99. if endSlash {
  100. reverse.WriteByte('/')
  101. }
  102. // Compile full regexp.
  103. reg, errCompile := regexp.Compile(pattern.String())
  104. if errCompile != nil {
  105. return nil, errCompile
  106. }
  107. // Check for capturing groups which used to work in older versions
  108. if reg.NumSubexp() != len(idxs)/2 {
  109. panic(fmt.Sprintf("route %s contains capture groups in its regexp. ", template) +
  110. "Only non-capturing groups are accepted: e.g. (?:pattern) instead of (pattern)")
  111. }
  112. // Done!
  113. return &routeRegexp{
  114. template: template,
  115. matchHost: matchHost,
  116. matchQuery: matchQuery,
  117. strictSlash: strictSlash,
  118. useEncodedPath: useEncodedPath,
  119. regexp: reg,
  120. reverse: reverse.String(),
  121. varsN: varsN,
  122. varsR: varsR,
  123. }, nil
  124. }
  125. // routeRegexp stores a regexp to match a host or path and information to
  126. // collect and validate route variables.
  127. type routeRegexp struct {
  128. // The unmodified template.
  129. template string
  130. // True for host match, false for path or query string match.
  131. matchHost bool
  132. // True for query string match, false for path and host match.
  133. matchQuery bool
  134. // The strictSlash value defined on the route, but disabled if PathPrefix was used.
  135. strictSlash bool
  136. // Determines whether to use encoded path from getPath function or unencoded
  137. // req.URL.Path for path matching
  138. useEncodedPath bool
  139. // Expanded regexp.
  140. regexp *regexp.Regexp
  141. // Reverse template.
  142. reverse string
  143. // Variable names.
  144. varsN []string
  145. // Variable regexps (validators).
  146. varsR []*regexp.Regexp
  147. }
  148. // Match matches the regexp against the URL host or path.
  149. func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool {
  150. if !r.matchHost {
  151. if r.matchQuery {
  152. return r.matchQueryString(req)
  153. }
  154. path := req.URL.Path
  155. if r.useEncodedPath {
  156. path = getPath(req)
  157. }
  158. return r.regexp.MatchString(path)
  159. }
  160. return r.regexp.MatchString(getHost(req))
  161. }
  162. // url builds a URL part using the given values.
  163. func (r *routeRegexp) url(values map[string]string) (string, error) {
  164. urlValues := make([]interface{}, len(r.varsN))
  165. for k, v := range r.varsN {
  166. value, ok := values[v]
  167. if !ok {
  168. return "", fmt.Errorf("mux: missing route variable %q", v)
  169. }
  170. urlValues[k] = value
  171. }
  172. rv := fmt.Sprintf(r.reverse, urlValues...)
  173. if !r.regexp.MatchString(rv) {
  174. // The URL is checked against the full regexp, instead of checking
  175. // individual variables. This is faster but to provide a good error
  176. // message, we check individual regexps if the URL doesn't match.
  177. for k, v := range r.varsN {
  178. if !r.varsR[k].MatchString(values[v]) {
  179. return "", fmt.Errorf(
  180. "mux: variable %q doesn't match, expected %q", values[v],
  181. r.varsR[k].String())
  182. }
  183. }
  184. }
  185. return rv, nil
  186. }
  187. // getURLQuery returns a single query parameter from a request URL.
  188. // For a URL with foo=bar&baz=ding, we return only the relevant key
  189. // value pair for the routeRegexp.
  190. func (r *routeRegexp) getURLQuery(req *http.Request) string {
  191. if !r.matchQuery {
  192. return ""
  193. }
  194. templateKey := strings.SplitN(r.template, "=", 2)[0]
  195. for key, vals := range req.URL.Query() {
  196. if key == templateKey && len(vals) > 0 {
  197. return key + "=" + vals[0]
  198. }
  199. }
  200. return ""
  201. }
  202. func (r *routeRegexp) matchQueryString(req *http.Request) bool {
  203. return r.regexp.MatchString(r.getURLQuery(req))
  204. }
  205. // braceIndices returns the first level curly brace indices from a string.
  206. // It returns an error in case of unbalanced braces.
  207. func braceIndices(s string) ([]int, error) {
  208. var level, idx int
  209. var idxs []int
  210. for i := 0; i < len(s); i++ {
  211. switch s[i] {
  212. case '{':
  213. if level++; level == 1 {
  214. idx = i
  215. }
  216. case '}':
  217. if level--; level == 0 {
  218. idxs = append(idxs, idx, i+1)
  219. } else if level < 0 {
  220. return nil, fmt.Errorf("mux: unbalanced braces in %q", s)
  221. }
  222. }
  223. }
  224. if level != 0 {
  225. return nil, fmt.Errorf("mux: unbalanced braces in %q", s)
  226. }
  227. return idxs, nil
  228. }
  229. // varGroupName builds a capturing group name for the indexed variable.
  230. func varGroupName(idx int) string {
  231. return "v" + strconv.Itoa(idx)
  232. }
  233. // ----------------------------------------------------------------------------
  234. // routeRegexpGroup
  235. // ----------------------------------------------------------------------------
  236. // routeRegexpGroup groups the route matchers that carry variables.
  237. type routeRegexpGroup struct {
  238. host *routeRegexp
  239. path *routeRegexp
  240. queries []*routeRegexp
  241. }
  242. // setMatch extracts the variables from the URL once a route matches.
  243. func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) {
  244. // Store host variables.
  245. if v.host != nil {
  246. host := getHost(req)
  247. matches := v.host.regexp.FindStringSubmatchIndex(host)
  248. if len(matches) > 0 {
  249. extractVars(host, matches, v.host.varsN, m.Vars)
  250. }
  251. }
  252. path := req.URL.Path
  253. if r.useEncodedPath {
  254. path = getPath(req)
  255. }
  256. // Store path variables.
  257. if v.path != nil {
  258. matches := v.path.regexp.FindStringSubmatchIndex(path)
  259. if len(matches) > 0 {
  260. extractVars(path, matches, v.path.varsN, m.Vars)
  261. // Check if we should redirect.
  262. if v.path.strictSlash {
  263. p1 := strings.HasSuffix(path, "/")
  264. p2 := strings.HasSuffix(v.path.template, "/")
  265. if p1 != p2 {
  266. u, _ := url.Parse(req.URL.String())
  267. if p1 {
  268. u.Path = u.Path[:len(u.Path)-1]
  269. } else {
  270. u.Path += "/"
  271. }
  272. m.Handler = http.RedirectHandler(u.String(), 301)
  273. }
  274. }
  275. }
  276. }
  277. // Store query string variables.
  278. for _, q := range v.queries {
  279. queryURL := q.getURLQuery(req)
  280. matches := q.regexp.FindStringSubmatchIndex(queryURL)
  281. if len(matches) > 0 {
  282. extractVars(queryURL, matches, q.varsN, m.Vars)
  283. }
  284. }
  285. }
  286. // getHost tries its best to return the request host.
  287. func getHost(r *http.Request) string {
  288. if r.URL.IsAbs() {
  289. return r.URL.Host
  290. }
  291. host := r.Host
  292. // Slice off any port information.
  293. if i := strings.Index(host, ":"); i != -1 {
  294. host = host[:i]
  295. }
  296. return host
  297. }
  298. func extractVars(input string, matches []int, names []string, output map[string]string) {
  299. for i, name := range names {
  300. output[name] = input[matches[2*i+2]:matches[2*i+3]]
  301. }
  302. }