trout
2016-01-21
Parent:3df515f0cec5
4:07a9b501d6b5 tip Browse Files
Add Router prefix. Make the Router use a prefix that will be stripped before matching URLs against Endpoints, so we can ignore the prefix that http.Handle is matching against, instead of duplicating it, which can lead to confusing 404s.
1.1 --- a/route.go Sat Jan 02 15:42:57 2016 -0800 1.2 +++ b/route.go Thu Jan 21 15:37:00 2016 -0800 1.3 @@ -56,6 +56,7 @@ 1.4 t *trie 1.5 Handle404 http.Handler 1.6 Handle405 http.Handler 1.7 + prefix string 1.8 } 1.9 1.10 func (router *Router) serve404(w http.ResponseWriter, r *http.Request, t time.Time) { 1.11 @@ -82,7 +83,8 @@ 1.12 router.serve404(w, r, start) 1.13 return 1.14 } 1.15 - pieces := strings.Split(strings.ToLower(strings.Trim(r.URL.Path, "/")), "/") 1.16 + u := strings.TrimPrefix(r.URL.Path, router.prefix) 1.17 + pieces := strings.Split(strings.ToLower(strings.Trim(u, "/")), "/") 1.18 router.t.RLock() 1.19 defer router.t.RUnlock() 1.20 branches := make([]*branch, len(pieces)) 1.21 @@ -116,6 +118,12 @@ 1.22 h.ServeHTTP(w, r) 1.23 } 1.24 1.25 +// SetPrefix sets a string prefix for the Router that won't be taken into account when matching Endpoints. 1.26 +// This is usually set to whatever path is associated with the http.Handler serving the Router. 1.27 +func (router *Router) SetPrefix(prefix string) { 1.28 + router.prefix = prefix 1.29 +} 1.30 + 1.31 // Endpoint defines a new Endpoint on the Router. The Endpoint should be a URL template, using curly braces 1.32 // to denote parameters that should be filled at runtime. For example, `{id}` denotes a parameter named `id` 1.33 // that should be filled with whatever the request has in that space.