regexp.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. "strings"
  12. )
  13. // newRouteRegexp parses a route template and returns a routeRegexp,
  14. // used to match a host or path.
  15. //
  16. // It will extract named variables, assemble a regexp to be matched, create
  17. // a "reverse" template to build URLs and compile regexps to validate variable
  18. // values used in URL building.
  19. //
  20. // Previously we accepted only Python-like identifiers for variable
  21. // names ([a-zA-Z_][a-zA-Z0-9_]*), but currently the only restriction is that
  22. // name and pattern can't be empty, and names can't contain a colon.
  23. func newRouteRegexp(tpl string, matchHost, matchPrefix, strictSlash bool) (*routeRegexp, error) {
  24. // Check if it is well-formed.
  25. idxs, errBraces := braceIndices(tpl)
  26. if errBraces != nil {
  27. return nil, errBraces
  28. }
  29. // Backup the original.
  30. template := tpl
  31. // Now let's parse it.
  32. defaultPattern := "[^/]+"
  33. if matchHost {
  34. defaultPattern = "[^.]+"
  35. matchPrefix, strictSlash = false, false
  36. }
  37. if matchPrefix {
  38. strictSlash = false
  39. }
  40. // Set a flag for strictSlash.
  41. endSlash := false
  42. if strictSlash && strings.HasSuffix(tpl, "/") {
  43. tpl = tpl[:len(tpl)-1]
  44. endSlash = true
  45. }
  46. varsN := make([]string, len(idxs)/2)
  47. varsR := make([]*regexp.Regexp, len(idxs)/2)
  48. pattern := bytes.NewBufferString("^")
  49. reverse := bytes.NewBufferString("")
  50. var end int
  51. var err error
  52. for i := 0; i < len(idxs); i += 2 {
  53. // Set all values we are interested in.
  54. raw := tpl[end:idxs[i]]
  55. end = idxs[i+1]
  56. parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2)
  57. name := parts[0]
  58. patt := defaultPattern
  59. if len(parts) == 2 {
  60. patt = parts[1]
  61. }
  62. // Name or pattern can't be empty.
  63. if name == "" || patt == "" {
  64. return nil, fmt.Errorf("mux: missing name or pattern in %q",
  65. tpl[idxs[i]:end])
  66. }
  67. // Build the regexp pattern.
  68. fmt.Fprintf(pattern, "%s(%s)", regexp.QuoteMeta(raw), patt)
  69. // Build the reverse template.
  70. fmt.Fprintf(reverse, "%s%%s", raw)
  71. // Append variable name and compiled pattern.
  72. varsN[i/2] = name
  73. varsR[i/2], err = regexp.Compile(fmt.Sprintf("^%s$", patt))
  74. if err != nil {
  75. return nil, err
  76. }
  77. }
  78. // Add the remaining.
  79. raw := tpl[end:]
  80. pattern.WriteString(regexp.QuoteMeta(raw))
  81. if strictSlash {
  82. pattern.WriteString("[/]?")
  83. }
  84. if !matchPrefix {
  85. pattern.WriteByte('$')
  86. }
  87. reverse.WriteString(raw)
  88. if endSlash {
  89. reverse.WriteByte('/')
  90. }
  91. // Compile full regexp.
  92. reg, errCompile := regexp.Compile(pattern.String())
  93. if errCompile != nil {
  94. return nil, errCompile
  95. }
  96. // Done!
  97. return &routeRegexp{
  98. template: template,
  99. matchHost: matchHost,
  100. regexp: reg,
  101. reverse: reverse.String(),
  102. varsN: varsN,
  103. varsR: varsR,
  104. }, nil
  105. }
  106. // routeRegexp stores a regexp to match a host or path and information to
  107. // collect and validate route variables.
  108. type routeRegexp struct {
  109. // The unmodified template.
  110. template string
  111. // True for host match, false for path match.
  112. matchHost bool
  113. // Expanded regexp.
  114. regexp *regexp.Regexp
  115. // Reverse template.
  116. reverse string
  117. // Variable names.
  118. varsN []string
  119. // Variable regexps (validators).
  120. varsR []*regexp.Regexp
  121. }
  122. // Match matches the regexp against the URL host or path.
  123. func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool {
  124. if !r.matchHost {
  125. return r.regexp.MatchString(req.URL.Path)
  126. }
  127. return r.regexp.MatchString(getHost(req))
  128. }
  129. // url builds a URL part using the given values.
  130. func (r *routeRegexp) url(pairs ...string) (string, error) {
  131. values, err := mapFromPairs(pairs...)
  132. if err != nil {
  133. return "", err
  134. }
  135. urlValues := make([]interface{}, len(r.varsN))
  136. for k, v := range r.varsN {
  137. value, ok := values[v]
  138. if !ok {
  139. return "", fmt.Errorf("mux: missing route variable %q", v)
  140. }
  141. urlValues[k] = value
  142. }
  143. rv := fmt.Sprintf(r.reverse, urlValues...)
  144. if !r.regexp.MatchString(rv) {
  145. // The URL is checked against the full regexp, instead of checking
  146. // individual variables. This is faster but to provide a good error
  147. // message, we check individual regexps if the URL doesn't match.
  148. for k, v := range r.varsN {
  149. if !r.varsR[k].MatchString(values[v]) {
  150. return "", fmt.Errorf(
  151. "mux: variable %q doesn't match, expected %q", values[v],
  152. r.varsR[k].String())
  153. }
  154. }
  155. }
  156. return rv, nil
  157. }
  158. // braceIndices returns the first level curly brace indices from a string.
  159. // It returns an error in case of unbalanced braces.
  160. func braceIndices(s string) ([]int, error) {
  161. var level, idx int
  162. idxs := make([]int, 0)
  163. for i := 0; i < len(s); i++ {
  164. switch s[i] {
  165. case '{':
  166. if level++; level == 1 {
  167. idx = i
  168. }
  169. case '}':
  170. if level--; level == 0 {
  171. idxs = append(idxs, idx, i+1)
  172. } else if level < 0 {
  173. return nil, fmt.Errorf("mux: unbalanced braces in %q", s)
  174. }
  175. }
  176. }
  177. if level != 0 {
  178. return nil, fmt.Errorf("mux: unbalanced braces in %q", s)
  179. }
  180. return idxs, nil
  181. }
  182. // ----------------------------------------------------------------------------
  183. // routeRegexpGroup
  184. // ----------------------------------------------------------------------------
  185. // routeRegexpGroup groups the route matchers that carry variables.
  186. type routeRegexpGroup struct {
  187. host *routeRegexp
  188. path *routeRegexp
  189. }
  190. // setMatch extracts the variables from the URL once a route matches.
  191. func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) {
  192. // Store host variables.
  193. if v.host != nil {
  194. hostVars := v.host.regexp.FindStringSubmatch(getHost(req))
  195. if hostVars != nil {
  196. for k, v := range v.host.varsN {
  197. m.Vars[v] = hostVars[k+1]
  198. }
  199. }
  200. }
  201. // Store path variables.
  202. if v.path != nil {
  203. pathVars := v.path.regexp.FindStringSubmatch(req.URL.Path)
  204. if pathVars != nil {
  205. for k, v := range v.path.varsN {
  206. m.Vars[v] = pathVars[k+1]
  207. }
  208. // Check if we should redirect.
  209. if r.strictSlash {
  210. p1 := strings.HasSuffix(req.URL.Path, "/")
  211. p2 := strings.HasSuffix(v.path.template, "/")
  212. if p1 != p2 {
  213. u, _ := url.Parse(req.URL.String())
  214. if p1 {
  215. u.Path = u.Path[:len(u.Path)-1]
  216. } else {
  217. u.Path += "/"
  218. }
  219. m.Handler = http.RedirectHandler(u.String(), 301)
  220. }
  221. }
  222. }
  223. }
  224. }
  225. // getHost tries its best to return the request host.
  226. func getHost(r *http.Request) string {
  227. if !r.URL.IsAbs() {
  228. host := r.Host
  229. // Slice off any port information.
  230. if i := strings.Index(host, ":"); i != -1 {
  231. host = host[:i]
  232. }
  233. return host
  234. }
  235. return r.URL.Host
  236. }