HomePhabricatorNo messages. No notifications. 5 unresolved issues.
Owners
None
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
5package mux
6
7import (
8"errors"
9"fmt"
10"net/http"
11"path"
12"regexp"
13)
14
15var (
16// ErrMethodMismatch is returned when the method in the request does not match
17// the method defined against the route.
18ErrMethodMismatch = errors.New("method is not allowed")
19// ErrNotFound is returned when no route match is found.
20ErrNotFound = errors.New("no matching route was found")
21)
22
23// NewRouter returns a new router instance.
24func NewRouter() *Router {
25return &Router{namedRoutes: make(map[string]*Route)}
26}
27
28// Router registers routes to be matched and dispatches a handler.
29//
30// It implements the http.Handler interface, so it can be registered to serve
31// requests:
32//
33// var router = mux.NewRouter()
34//
35// func main() {
36// http.Handle("/", router)
37// }
38//
39// Or, for Google App Engine, register it in a init() function:
40//
41// func init() {
42// http.Handle("/", router)
43// }
44//
45// This will send all incoming requests to the router.
46type Router struct {
47// Configurable Handler to be used when no route matches.
48NotFoundHandler http.Handler
49
50// Configurable Handler to be used when the request method does not match the route.
51MethodNotAllowedHandler http.Handler
52
53// Routes to be matched, in order.
54routes []*Route
55
56// Routes by name for URL building.
57namedRoutes map[string]*Route
58
59// If true, do not clear the request context after handling the request.
60//
61// Deprecated: No effect when go1.7+ is used, since the context is stored
62// on the request itself.
63KeepContext bool
64
65// Slice of middlewares to be called after a match is found
66middlewares []middleware
67
68// configuration shared with `Route`
69routeConf
70}
71
72// common route configuration shared between `Router` and `Route`
73type routeConf struct {
74// If true, "/path/foo%2Fbar/to" will match the path "/path/{var}/to"
75useEncodedPath bool
76
77// If true, when the path pattern is "/path/", accessing "/path" will
78// redirect to the former and vice versa.
79strictSlash bool
80
81// If true, when the path pattern is "/path//to", accessing "/path//to"
82// will not redirect
83skipClean bool
84
85// Manager for the variables from host and path.
86regexp routeRegexpGroup
87
88// List of matchers.
89matchers []matcher
90
91// The scheme used when building URLs.
92buildScheme string
93
94buildVarsFunc BuildVarsFunc
95}
96
97// returns an effective deep copy of `routeConf`
98func copyRouteConf(r routeConf) routeConf {
99c := r
100
101if r.regexp.path != nil {
102c.regexp.path = copyRouteRegexp(r.regexp.path)
103}
104
105if r.regexp.host != nil {
106c.regexp.host = copyRouteRegexp(r.regexp.host)
107}
108
109c.regexp.queries = make([]*routeRegexp, 0, len(r.regexp.queries))
110for _, q := range r.regexp.queries {
111c.regexp.queries = append(c.regexp.queries, copyRouteRegexp(q))
112}
113
114c.matchers = make([]matcher, len(r.matchers))
115copy(c.matchers, r.matchers)
116
117return c
118}
119
120func copyRouteRegexp(r *routeRegexp) *routeRegexp {
121c := *r
122return &c
123}
124
125// Match attempts to match the given request against the router's registered routes.
126//
127// If the request matches a route of this router or one of its subrouters the Route,
128// Handler, and Vars fields of the the match argument are filled and this function
129// returns true.
130//
131// If the request does not match any of this router's or its subrouters' routes
132// then this function returns false. If available, a reason for the match failure
133// will be filled in the match argument's MatchErr field. If the match failure type
134// (eg: not found) has a registered handler, the handler is assigned to the Handler
135// field of the match argument.
136func (r *Router) Match(req *http.Request, match *RouteMatch) bool {
137for _, route := range r.routes {
138if route.Match(req, match) {
139// Build middleware chain if no error was found
140if match.MatchErr == nil {
141for i := len(r.middlewares) - 1; i >= 0; i-- {
142match.Handler = r.middlewares[i].Middleware(match.Handler)
143}
144}
145return true
146}
147}
148
149if match.MatchErr == ErrMethodMismatch {
150if r.MethodNotAllowedHandler != nil {
151match.Handler = r.MethodNotAllowedHandler
152return true
153}
154
155return false
156}
157
158// Closest match for a router (includes sub-routers)
159if r.NotFoundHandler != nil {
160match.Handler = r.NotFoundHandler
161match.MatchErr = ErrNotFound
162return true
163}
164
165match.MatchErr = ErrNotFound
166return false
167}
168
169// ServeHTTP dispatches the handler registered in the matched route.
170//
171// When there is a match, the route variables can be retrieved calling
172// mux.Vars(request).
173func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
174if !r.skipClean {
175path := req.URL.Path
176if r.useEncodedPath {
177path = req.URL.EscapedPath()
178}
179// Clean path to canonical form and redirect.
180if p := cleanPath(path); p != path {
181
182// Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query.
183// This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue:
184// http://code.google.com/p/go/issues/detail?id=5252
185url := *req.URL
186url.Path = p
187p = url.String()
188
189w.Header().Set("Location", p)
190w.WriteHeader(http.StatusMovedPermanently)
191return
192}
193}
194var match RouteMatch
195var handler http.Handler
196if r.Match(req, &match) {
197handler = match.Handler
198req = setVars(req, match.Vars)
199req = setCurrentRoute(req, match.Route)
200}
201
202if handler == nil && match.MatchErr == ErrMethodMismatch {
203handler = methodNotAllowedHandler()
204}
205
206if handler == nil {
207handler = http.NotFoundHandler()
208}
209
210handler.ServeHTTP(w, req)
211}
212
213// Get returns a route registered with the given name.
214func (r *Router) Get(name string) *Route {
215return r.namedRoutes[name]
216}
217
218// GetRoute returns a route registered with the given name. This method
219// was renamed to Get() and remains here for backwards compatibility.
220func (r *Router) GetRoute(name string) *Route {
221return r.namedRoutes[name]
222}
223
224// StrictSlash defines the trailing slash behavior for new routes. The initial
225// value is false.
226//
227// When true, if the route path is "/path/", accessing "/path" will perform a redirect
228// to the former and vice versa. In other words, your application will always
229// see the path as specified in the route.
230//
231// When false, if the route path is "/path", accessing "/path/" will not match
232// this route and vice versa.
233//
234// The re-direct is a HTTP 301 (Moved Permanently). Note that when this is set for
235// routes with a non-idempotent method (e.g. POST, PUT), the subsequent re-directed
236// request will be made as a GET by most clients. Use middleware or client settings
237// to modify this behaviour as needed.
238//
239// Special case: when a route sets a path prefix using the PathPrefix() method,
240// strict slash is ignored for that route because the redirect behavior can't
241// be determined from a prefix alone. However, any subrouters created from that
242// route inherit the original StrictSlash setting.
243func (r *Router) StrictSlash(value bool) *Router {
244r.strictSlash = value
245return r
246}
247
248// SkipClean defines the path cleaning behaviour for new routes. The initial
249// value is false. Users should be careful about which routes are not cleaned
250//
251// When true, if the route path is "/path//to", it will remain with the double
252// slash. This is helpful if you have a route like: /fetch/http://xkcd.com/534/
253//
254// When false, the path will be cleaned, so /fetch/http://xkcd.com/534/ will
255// become /fetch/http/xkcd.com/534
256func (r *Router) SkipClean(value bool) *Router {
257r.skipClean = value
258return r
259}
260
261// UseEncodedPath tells the router to match the encoded original path
262// to the routes.
263// For eg. "/path/foo%2Fbar/to" will match the path "/path/{var}/to".
264//
265// If not called, the router will match the unencoded path to the routes.
266// For eg. "/path/foo%2Fbar/to" will match the path "/path/foo/bar/to"
267func (r *Router) UseEncodedPath() *Router {
268r.useEncodedPath = true
269return r
270}
271
272// ----------------------------------------------------------------------------
273// Route factories
274// ----------------------------------------------------------------------------
275
276// NewRoute registers an empty route.
277func (r *Router) NewRoute() *Route {
278// initialize a route with a copy of the parent router's configuration
279route := &Route{routeConf: copyRouteConf(r.routeConf), namedRoutes: r.namedRoutes}
280r.routes = append(r.routes, route)
281return route
282}
283
284// Name registers a new route with a name.
285// See Route.Name().
286func (r *Router) Name(name string) *Route {
287return r.NewRoute().Name(name)
288}
289
290// Handle registers a new route with a matcher for the URL path.
291// See Route.Path() and Route.Handler().
292func (r *Router) Handle(path string, handler http.Handler) *Route {
293return r.NewRoute().Path(path).Handler(handler)
294}
295
296// HandleFunc registers a new route with a matcher for the URL path.
297// See Route.Path() and Route.HandlerFunc().
298func (r *Router) HandleFunc(path string, f func(http.ResponseWriter,
299*http.Request)) *Route {
300return r.NewRoute().Path(path).HandlerFunc(f)
301}
302
303// Headers registers a new route with a matcher for request header values.
304// See Route.Headers().
305func (r *Router) Headers(pairs ...string) *Route {
306return r.NewRoute().Headers(pairs...)
307}
308
309// Host registers a new route with a matcher for the URL host.
310// See Route.Host().
311func (r *Router) Host(tpl string) *Route {
312return r.NewRoute().Host(tpl)
313}
314
315// MatcherFunc registers a new route with a custom matcher function.
316// See Route.MatcherFunc().
317func (r *Router) MatcherFunc(f MatcherFunc) *Route {
318return r.NewRoute().MatcherFunc(f)
319}
320
321// Methods registers a new route with a matcher for HTTP methods.
322// See Route.Methods().
323func (r *Router) Methods(methods ...string) *Route {
324return r.NewRoute().Methods(methods...)
325}
326
327// Path registers a new route with a matcher for the URL path.
328// See Route.Path().
329func (r *Router) Path(tpl string) *Route {
330return r.NewRoute().Path(tpl)
331}
332
333// PathPrefix registers a new route with a matcher for the URL path prefix.
334// See Route.PathPrefix().
335func (r *Router) PathPrefix(tpl string) *Route {
336return r.NewRoute().PathPrefix(tpl)
337}
338
339// Queries registers a new route with a matcher for URL query values.
340// See Route.Queries().
341func (r *Router) Queries(pairs ...string) *Route {
342return r.NewRoute().Queries(pairs...)
343}
344
345// Schemes registers a new route with a matcher for URL schemes.
346// See Route.Schemes().
347func (r *Router) Schemes(schemes ...string) *Route {
348return r.NewRoute().Schemes(schemes...)
349}
350
351// BuildVarsFunc registers a new route with a custom function for modifying
352// route variables before building a URL.
353func (r *Router) BuildVarsFunc(f BuildVarsFunc) *Route {
354return r.NewRoute().BuildVarsFunc(f)
355}
356
357// Walk walks the router and all its sub-routers, calling walkFn for each route
358// in the tree. The routes are walked in the order they were added. Sub-routers
359// are explored depth-first.
360func (r *Router) Walk(walkFn WalkFunc) error {
361return r.walk(walkFn, []*Route{})
362}
363
364// SkipRouter is used as a return value from WalkFuncs to indicate that the
365// router that walk is about to descend down to should be skipped.
366var SkipRouter = errors.New("skip this router")
367
368// WalkFunc is the type of the function called for each route visited by Walk.
369// At every invocation, it is given the current route, and the current router,
370// and a list of ancestor routes that lead to the current route.
371type WalkFunc func(route *Route, router *Router, ancestors []*Route) error
372
373func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error {
374for _, t := range r.routes {
375err := walkFn(t, r, ancestors)
376if err == SkipRouter {
377continue
378}
379if err != nil {
380return err
381}
382for _, sr := range t.matchers {
383if h, ok := sr.(*Router); ok {
384ancestors = append(ancestors, t)
385err := h.walk(walkFn, ancestors)
386if err != nil {
387return err
388}
389ancestors = ancestors[:len(ancestors)-1]
390}
391}
392if h, ok := t.handler.(*Router); ok {
393ancestors = append(ancestors, t)
394err := h.walk(walkFn, ancestors)
395if err != nil {
396return err
397}
398ancestors = ancestors[:len(ancestors)-1]
399}
400}
401return nil
402}
403
404// ----------------------------------------------------------------------------
405// Context
406// ----------------------------------------------------------------------------
407
408// RouteMatch stores information about a matched route.
409type RouteMatch struct {
410Route *Route
411Handler http.Handler
412Vars map[string]string
413
414// MatchErr is set to appropriate matching error
415// It is set to ErrMethodMismatch if there is a mismatch in
416// the request method and route method
417MatchErr error
418}
419
420type contextKey int
421
422const (
423varsKey contextKey = iota
424routeKey
425)
426
427// Vars returns the route variables for the current request, if any.
428func Vars(r *http.Request) map[string]string {
429if rv := contextGet(r, varsKey); rv != nil {
430return rv.(map[string]string)
431}
432return nil
433}
434
435// CurrentRoute returns the matched route for the current request, if any.
436// This only works when called inside the handler of the matched route
437// because the matched route is stored in the request context which is cleared
438// after the handler returns, unless the KeepContext option is set on the
439// Router.
440func CurrentRoute(r *http.Request) *Route {
441if rv := contextGet(r, routeKey); rv != nil {
442return rv.(*Route)
443}
444return nil
445}
446
447func setVars(r *http.Request, val interface{}) *http.Request {
448return contextSet(r, varsKey, val)
449}
450
451func setCurrentRoute(r *http.Request, val interface{}) *http.Request {
452return contextSet(r, routeKey, val)
453}
454
455// ----------------------------------------------------------------------------
456// Helpers
457// ----------------------------------------------------------------------------
458
459// cleanPath returns the canonical path for p, eliminating . and .. elements.
460// Borrowed from the net/http package.
461func cleanPath(p string) string {
462if p == "" {
463return "/"
464}
465if p[0] != '/' {
466p = "/" + p
467}
468np := path.Clean(p)
469// path.Clean removes trailing slash except for root;
470// put the trailing slash back if necessary.
471if p[len(p)-1] == '/' && np != "/" {
472np += "/"
473}
474
475return np
476}
477
478// uniqueVars returns an error if two slices contain duplicated strings.
479func uniqueVars(s1, s2 []string) error {
480for _, v1 := range s1 {
481for _, v2 := range s2 {
482if v1 == v2 {
483return fmt.Errorf("mux: duplicated route variable %q", v2)
484}
485}
486}
487return nil
488}
489
490// checkPairs returns the count of strings passed in, and an error if
491// the count is not an even number.
492func checkPairs(pairs ...string) (int, error) {
493length := len(pairs)
494if length%2 != 0 {
495return length, fmt.Errorf(
496"mux: number of parameters must be multiple of 2, got %v", pairs)
497}
498return length, nil
499}
500
501// mapFromPairsToString converts variadic string parameters to a
502// string to string map.
503func mapFromPairsToString(pairs ...string) (map[string]string, error) {
504length, err := checkPairs(pairs...)
505if err != nil {
506return nil, err
507}
508m := make(map[string]string, length/2)
509for i := 0; i < length; i += 2 {
510m[pairs[i]] = pairs[i+1]
511}
512return m, nil
513}
514
515// mapFromPairsToRegex converts variadic string parameters to a
516// string to regex map.
517func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) {
518length, err := checkPairs(pairs...)
519if err != nil {
520return nil, err
521}
522m := make(map[string]*regexp.Regexp, length/2)
523for i := 0; i < length; i += 2 {
524regex, err := regexp.Compile(pairs[i+1])
525if err != nil {
526return nil, err
527}
528m[pairs[i]] = regex
529}
530return m, nil
531}
532
533// matchInArray returns true if the given string value is in the array.
534func matchInArray(arr []string, value string) bool {
535for _, v := range arr {
536if v == value {
537return true
538}
539}
540return false
541}
542
543// matchMapWithString returns true if the given key/value pairs exist in a given map.
544func matchMapWithString(toCheck map[string]string, toMatch map[string][]string, canonicalKey bool) bool {
545for k, v := range toCheck {
546// Check if key exists.
547if canonicalKey {
548k = http.CanonicalHeaderKey(k)
549}
550if values := toMatch[k]; values == nil {
551return false
552} else if v != "" {
553// If value was defined as an empty string we only check that the
554// key exists. Otherwise we also check for equality.
555valueExists := false
556for _, value := range values {
557if v == value {
558valueExists = true
559break
560}
561}
562if !valueExists {
563return false
564}
565}
566}
567return true
568}
569
570// matchMapWithRegex returns true if the given key/value pairs exist in a given map compiled against
571// the given regex
572func matchMapWithRegex(toCheck map[string]*regexp.Regexp, toMatch map[string][]string, canonicalKey bool) bool {
573for k, v := range toCheck {
574// Check if key exists.
575if canonicalKey {
576k = http.CanonicalHeaderKey(k)
577}
578if values := toMatch[k]; values == nil {
579return false
580} else if v != nil {
581// If value was defined as an empty string we only check that the
582// key exists. Otherwise we also check for equality.
583valueExists := false
584for _, value := range values {
585if v.MatchString(value) {
586valueExists = true
587break
588}
589}
590if !valueExists {
591return false
592}
593}
594}
595return true
596}
597
598// methodNotAllowed replies to the request with an HTTP status code 405.
599func methodNotAllowed(w http.ResponseWriter, r *http.Request) {
600w.WriteHeader(http.StatusMethodNotAllowed)
601}
602
603// methodNotAllowedHandler returns a simple request handler
604// that replies to each request with a status code 405.
605func methodNotAllowedHandler() http.Handler { return http.HandlerFunc(methodNotAllowed) }