mux.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. "fmt"
  7. "net/http"
  8. "path"
  9. "github.com/coreos/etcd/third_party/github.com/gorilla/context"
  10. )
  11. // NewRouter returns a new router instance.
  12. func NewRouter() *Router {
  13. return &Router{namedRoutes: make(map[string]*Route), KeepContext: false}
  14. }
  15. // Router registers routes to be matched and dispatches a handler.
  16. //
  17. // It implements the http.Handler interface, so it can be registered to serve
  18. // requests:
  19. //
  20. // var router = mux.NewRouter()
  21. //
  22. // func main() {
  23. // http.Handle("/", router)
  24. // }
  25. //
  26. // Or, for Google App Engine, register it in a init() function:
  27. //
  28. // func init() {
  29. // http.Handle("/", router)
  30. // }
  31. //
  32. // This will send all incoming requests to the router.
  33. type Router struct {
  34. // Configurable Handler to be used when no route matches.
  35. NotFoundHandler http.Handler
  36. // Parent route, if this is a subrouter.
  37. parent parentRoute
  38. // Routes to be matched, in order.
  39. routes []*Route
  40. // Routes by name for URL building.
  41. namedRoutes map[string]*Route
  42. // See Router.StrictSlash(). This defines the flag for new routes.
  43. strictSlash bool
  44. // If true, do not clear the request context after handling the request
  45. KeepContext bool
  46. }
  47. // Match matches registered routes against the request.
  48. func (r *Router) Match(req *http.Request, match *RouteMatch) bool {
  49. for _, route := range r.routes {
  50. if route.Match(req, match) {
  51. return true
  52. }
  53. }
  54. return false
  55. }
  56. // ServeHTTP dispatches the handler registered in the matched route.
  57. //
  58. // When there is a match, the route variables can be retrieved calling
  59. // mux.Vars(request).
  60. func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  61. // Clean path to canonical form and redirect.
  62. if p := cleanPath(req.URL.Path); p != req.URL.Path {
  63. // Added 3 lines (Philip Schlump) - It was droping the query string and #whatever from query.
  64. // This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue:
  65. // http://code.google.com/p/go/issues/detail?id=5252
  66. url := *req.URL
  67. url.Path = p
  68. p = url.String()
  69. w.Header().Set("Location", p)
  70. w.WriteHeader(http.StatusMovedPermanently)
  71. return
  72. }
  73. var match RouteMatch
  74. var handler http.Handler
  75. if r.Match(req, &match) {
  76. handler = match.Handler
  77. setVars(req, match.Vars)
  78. setCurrentRoute(req, match.Route)
  79. }
  80. if handler == nil {
  81. if r.NotFoundHandler == nil {
  82. r.NotFoundHandler = http.NotFoundHandler()
  83. }
  84. handler = r.NotFoundHandler
  85. }
  86. if !r.KeepContext {
  87. defer context.Clear(req)
  88. }
  89. handler.ServeHTTP(w, req)
  90. }
  91. // Get returns a route registered with the given name.
  92. func (r *Router) Get(name string) *Route {
  93. return r.getNamedRoutes()[name]
  94. }
  95. // GetRoute returns a route registered with the given name. This method
  96. // was renamed to Get() and remains here for backwards compatibility.
  97. func (r *Router) GetRoute(name string) *Route {
  98. return r.getNamedRoutes()[name]
  99. }
  100. // StrictSlash defines the slash behavior for new routes.
  101. //
  102. // When true, if the route path is "/path/", accessing "/path" will redirect
  103. // to the former and vice versa.
  104. //
  105. // Special case: when a route sets a path prefix, strict slash is
  106. // automatically set to false for that route because the redirect behavior
  107. // can't be determined for prefixes.
  108. func (r *Router) StrictSlash(value bool) *Router {
  109. r.strictSlash = value
  110. return r
  111. }
  112. // ----------------------------------------------------------------------------
  113. // parentRoute
  114. // ----------------------------------------------------------------------------
  115. // getNamedRoutes returns the map where named routes are registered.
  116. func (r *Router) getNamedRoutes() map[string]*Route {
  117. if r.namedRoutes == nil {
  118. if r.parent != nil {
  119. r.namedRoutes = r.parent.getNamedRoutes()
  120. } else {
  121. r.namedRoutes = make(map[string]*Route)
  122. }
  123. }
  124. return r.namedRoutes
  125. }
  126. // getRegexpGroup returns regexp definitions from the parent route, if any.
  127. func (r *Router) getRegexpGroup() *routeRegexpGroup {
  128. if r.parent != nil {
  129. return r.parent.getRegexpGroup()
  130. }
  131. return nil
  132. }
  133. // ----------------------------------------------------------------------------
  134. // Route factories
  135. // ----------------------------------------------------------------------------
  136. // NewRoute registers an empty route.
  137. func (r *Router) NewRoute() *Route {
  138. route := &Route{parent: r, strictSlash: r.strictSlash}
  139. r.routes = append(r.routes, route)
  140. return route
  141. }
  142. // Handle registers a new route with a matcher for the URL path.
  143. // See Route.Path() and Route.Handler().
  144. func (r *Router) Handle(path string, handler http.Handler) *Route {
  145. return r.NewRoute().Path(path).Handler(handler)
  146. }
  147. // HandleFunc registers a new route with a matcher for the URL path.
  148. // See Route.Path() and Route.HandlerFunc().
  149. func (r *Router) HandleFunc(path string, f func(http.ResponseWriter,
  150. *http.Request)) *Route {
  151. return r.NewRoute().Path(path).HandlerFunc(f)
  152. }
  153. // Headers registers a new route with a matcher for request header values.
  154. // See Route.Headers().
  155. func (r *Router) Headers(pairs ...string) *Route {
  156. return r.NewRoute().Headers(pairs...)
  157. }
  158. // Host registers a new route with a matcher for the URL host.
  159. // See Route.Host().
  160. func (r *Router) Host(tpl string) *Route {
  161. return r.NewRoute().Host(tpl)
  162. }
  163. // MatcherFunc registers a new route with a custom matcher function.
  164. // See Route.MatcherFunc().
  165. func (r *Router) MatcherFunc(f MatcherFunc) *Route {
  166. return r.NewRoute().MatcherFunc(f)
  167. }
  168. // Methods registers a new route with a matcher for HTTP methods.
  169. // See Route.Methods().
  170. func (r *Router) Methods(methods ...string) *Route {
  171. return r.NewRoute().Methods(methods...)
  172. }
  173. // Path registers a new route with a matcher for the URL path.
  174. // See Route.Path().
  175. func (r *Router) Path(tpl string) *Route {
  176. return r.NewRoute().Path(tpl)
  177. }
  178. // PathPrefix registers a new route with a matcher for the URL path prefix.
  179. // See Route.PathPrefix().
  180. func (r *Router) PathPrefix(tpl string) *Route {
  181. return r.NewRoute().PathPrefix(tpl)
  182. }
  183. // Queries registers a new route with a matcher for URL query values.
  184. // See Route.Queries().
  185. func (r *Router) Queries(pairs ...string) *Route {
  186. return r.NewRoute().Queries(pairs...)
  187. }
  188. // Schemes registers a new route with a matcher for URL schemes.
  189. // See Route.Schemes().
  190. func (r *Router) Schemes(schemes ...string) *Route {
  191. return r.NewRoute().Schemes(schemes...)
  192. }
  193. // ----------------------------------------------------------------------------
  194. // Context
  195. // ----------------------------------------------------------------------------
  196. // RouteMatch stores information about a matched route.
  197. type RouteMatch struct {
  198. Route *Route
  199. Handler http.Handler
  200. Vars map[string]string
  201. }
  202. type contextKey int
  203. const (
  204. varsKey contextKey = iota
  205. routeKey
  206. )
  207. // Vars returns the route variables for the current request, if any.
  208. func Vars(r *http.Request) map[string]string {
  209. if rv := context.Get(r, varsKey); rv != nil {
  210. return rv.(map[string]string)
  211. }
  212. return nil
  213. }
  214. // CurrentRoute returns the matched route for the current request, if any.
  215. func CurrentRoute(r *http.Request) *Route {
  216. if rv := context.Get(r, routeKey); rv != nil {
  217. return rv.(*Route)
  218. }
  219. return nil
  220. }
  221. func setVars(r *http.Request, val interface{}) {
  222. context.Set(r, varsKey, val)
  223. }
  224. func setCurrentRoute(r *http.Request, val interface{}) {
  225. context.Set(r, routeKey, val)
  226. }
  227. // ----------------------------------------------------------------------------
  228. // Helpers
  229. // ----------------------------------------------------------------------------
  230. // cleanPath returns the canonical path for p, eliminating . and .. elements.
  231. // Borrowed from the net/http package.
  232. func cleanPath(p string) string {
  233. if p == "" {
  234. return "/"
  235. }
  236. if p[0] != '/' {
  237. p = "/" + p
  238. }
  239. np := path.Clean(p)
  240. // path.Clean removes trailing slash except for root;
  241. // put the trailing slash back if necessary.
  242. if p[len(p)-1] == '/' && np != "/" {
  243. np += "/"
  244. }
  245. return np
  246. }
  247. // uniqueVars returns an error if two slices contain duplicated strings.
  248. func uniqueVars(s1, s2 []string) error {
  249. for _, v1 := range s1 {
  250. for _, v2 := range s2 {
  251. if v1 == v2 {
  252. return fmt.Errorf("mux: duplicated route variable %q", v2)
  253. }
  254. }
  255. }
  256. return nil
  257. }
  258. // mapFromPairs converts variadic string parameters to a string map.
  259. func mapFromPairs(pairs ...string) (map[string]string, error) {
  260. length := len(pairs)
  261. if length%2 != 0 {
  262. return nil, fmt.Errorf(
  263. "mux: number of parameters must be multiple of 2, got %v", pairs)
  264. }
  265. m := make(map[string]string, length/2)
  266. for i := 0; i < length; i += 2 {
  267. m[pairs[i]] = pairs[i+1]
  268. }
  269. return m, nil
  270. }
  271. // matchInArray returns true if the given string value is in the array.
  272. func matchInArray(arr []string, value string) bool {
  273. for _, v := range arr {
  274. if v == value {
  275. return true
  276. }
  277. }
  278. return false
  279. }
  280. // matchMap returns true if the given key/value pairs exist in a given map.
  281. func matchMap(toCheck map[string]string, toMatch map[string][]string,
  282. canonicalKey bool) bool {
  283. for k, v := range toCheck {
  284. // Check if key exists.
  285. if canonicalKey {
  286. k = http.CanonicalHeaderKey(k)
  287. }
  288. if values := toMatch[k]; values == nil {
  289. return false
  290. } else if v != "" {
  291. // If value was defined as an empty string we only check that the
  292. // key exists. Otherwise we also check for equality.
  293. valueExists := false
  294. for _, value := range values {
  295. if v == value {
  296. valueExists = true
  297. break
  298. }
  299. }
  300. if !valueExists {
  301. return false
  302. }
  303. }
  304. }
  305. return true
  306. }