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.
 
 
 

313 lines
8.3 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 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. // Done!
  108. return &routeRegexp{
  109. template: template,
  110. matchHost: matchHost,
  111. matchQuery: matchQuery,
  112. strictSlash: strictSlash,
  113. regexp: reg,
  114. reverse: reverse.String(),
  115. varsN: varsN,
  116. varsR: varsR,
  117. }, nil
  118. }
  119. // routeRegexp stores a regexp to match a host or path and information to
  120. // collect and validate route variables.
  121. type routeRegexp struct {
  122. // The unmodified template.
  123. template string
  124. // True for host match, false for path or query string match.
  125. matchHost bool
  126. // True for query string match, false for path and host match.
  127. matchQuery bool
  128. // The strictSlash value defined on the route, but disabled if PathPrefix was used.
  129. strictSlash bool
  130. // Expanded regexp.
  131. regexp *regexp.Regexp
  132. // Reverse template.
  133. reverse string
  134. // Variable names.
  135. varsN []string
  136. // Variable regexps (validators).
  137. varsR []*regexp.Regexp
  138. }
  139. // Match matches the regexp against the URL host or path.
  140. func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool {
  141. if !r.matchHost {
  142. if r.matchQuery {
  143. return r.matchQueryString(req)
  144. }
  145. return r.regexp.MatchString(req.URL.Path)
  146. }
  147. return r.regexp.MatchString(getHost(req))
  148. }
  149. // url builds a URL part using the given values.
  150. func (r *routeRegexp) url(values map[string]string) (string, error) {
  151. urlValues := make([]interface{}, len(r.varsN))
  152. for k, v := range r.varsN {
  153. value, ok := values[v]
  154. if !ok {
  155. return "", fmt.Errorf("mux: missing route variable %q", v)
  156. }
  157. urlValues[k] = value
  158. }
  159. rv := fmt.Sprintf(r.reverse, urlValues...)
  160. if !r.regexp.MatchString(rv) {
  161. // The URL is checked against the full regexp, instead of checking
  162. // individual variables. This is faster but to provide a good error
  163. // message, we check individual regexps if the URL doesn't match.
  164. for k, v := range r.varsN {
  165. if !r.varsR[k].MatchString(values[v]) {
  166. return "", fmt.Errorf(
  167. "mux: variable %q doesn't match, expected %q", values[v],
  168. r.varsR[k].String())
  169. }
  170. }
  171. }
  172. return rv, nil
  173. }
  174. // getURLQuery returns a single query parameter from a request URL.
  175. // For a URL with foo=bar&baz=ding, we return only the relevant key
  176. // value pair for the routeRegexp.
  177. func (r *routeRegexp) getURLQuery(req *http.Request) string {
  178. if !r.matchQuery {
  179. return ""
  180. }
  181. templateKey := strings.SplitN(r.template, "=", 2)[0]
  182. for key, vals := range req.URL.Query() {
  183. if key == templateKey && len(vals) > 0 {
  184. return key + "=" + vals[0]
  185. }
  186. }
  187. return ""
  188. }
  189. func (r *routeRegexp) matchQueryString(req *http.Request) bool {
  190. return r.regexp.MatchString(r.getURLQuery(req))
  191. }
  192. // braceIndices returns the first level curly brace indices from a string.
  193. // It returns an error in case of unbalanced braces.
  194. func braceIndices(s string) ([]int, error) {
  195. var level, idx int
  196. var idxs []int
  197. for i := 0; i < len(s); i++ {
  198. switch s[i] {
  199. case '{':
  200. if level++; level == 1 {
  201. idx = i
  202. }
  203. case '}':
  204. if level--; level == 0 {
  205. idxs = append(idxs, idx, i+1)
  206. } else if level < 0 {
  207. return nil, fmt.Errorf("mux: unbalanced braces in %q", s)
  208. }
  209. }
  210. }
  211. if level != 0 {
  212. return nil, fmt.Errorf("mux: unbalanced braces in %q", s)
  213. }
  214. return idxs, nil
  215. }
  216. // varGroupName builds a capturing group name for the indexed variable.
  217. func varGroupName(idx int) string {
  218. return "v" + strconv.Itoa(idx)
  219. }
  220. // ----------------------------------------------------------------------------
  221. // routeRegexpGroup
  222. // ----------------------------------------------------------------------------
  223. // routeRegexpGroup groups the route matchers that carry variables.
  224. type routeRegexpGroup struct {
  225. host *routeRegexp
  226. path *routeRegexp
  227. queries []*routeRegexp
  228. }
  229. // setMatch extracts the variables from the URL once a route matches.
  230. func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) {
  231. // Store host variables.
  232. if v.host != nil {
  233. host := getHost(req)
  234. matches := v.host.regexp.FindStringSubmatchIndex(host)
  235. if len(matches) > 0 {
  236. extractVars(host, matches, v.host.varsN, m.Vars)
  237. }
  238. }
  239. // Store path variables.
  240. if v.path != nil {
  241. matches := v.path.regexp.FindStringSubmatchIndex(req.URL.Path)
  242. if len(matches) > 0 {
  243. extractVars(req.URL.Path, matches, v.path.varsN, m.Vars)
  244. // Check if we should redirect.
  245. if v.path.strictSlash {
  246. p1 := strings.HasSuffix(req.URL.Path, "/")
  247. p2 := strings.HasSuffix(v.path.template, "/")
  248. if p1 != p2 {
  249. u, _ := url.Parse(req.URL.String())
  250. if p1 {
  251. u.Path = u.Path[:len(u.Path)-1]
  252. } else {
  253. u.Path += "/"
  254. }
  255. m.Handler = http.RedirectHandler(u.String(), 301)
  256. }
  257. }
  258. }
  259. }
  260. // Store query string variables.
  261. for _, q := range v.queries {
  262. queryURL := q.getURLQuery(req)
  263. matches := q.regexp.FindStringSubmatchIndex(queryURL)
  264. if len(matches) > 0 {
  265. extractVars(queryURL, matches, q.varsN, m.Vars)
  266. }
  267. }
  268. }
  269. // getHost tries its best to return the request host.
  270. func getHost(r *http.Request) string {
  271. if r.URL.IsAbs() {
  272. return r.URL.Host
  273. }
  274. host := r.Host
  275. // Slice off any port information.
  276. if i := strings.Index(host, ":"); i != -1 {
  277. host = host[:i]
  278. }
  279. return host
  280. }
  281. func extractVars(input string, matches []int, names []string, output map[string]string) {
  282. matchesCount := 0
  283. prevEnd := -1
  284. for i := 2; i < len(matches) && matchesCount < len(names); i += 2 {
  285. if prevEnd < matches[i+1] {
  286. value := input[matches[i]:matches[i+1]]
  287. output[names[matchesCount]] = value
  288. prevEnd = matches[i+1]
  289. matchesCount++
  290. }
  291. }
  292. }