From ff41f8eaa2cfdd22e7e2f36769f9343aaee16147 Mon Sep 17 00:00:00 2001 From: Carl Jackson Date: Sat, 30 May 2015 18:03:49 -0400 Subject: [PATCH] middleware: Make SubRouter Match-aware This helps avoid a gotcha when using matches with sub-routers. Fixes #120. --- web/middleware/subrouter.go | 14 ++++++++++++++ web/middleware/subrouter_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 web/middleware/subrouter_test.go diff --git a/web/middleware/subrouter.go b/web/middleware/subrouter.go index 1b3f3f3..1d371a7 100644 --- a/web/middleware/subrouter.go +++ b/web/middleware/subrouter.go @@ -19,9 +19,23 @@ func (s subrouter) ServeHTTP(w http.ResponseWriter, r *http.Request) { } if ok { oldpath := r.URL.Path + oldmatch := web.GetMatch(*s.c) r.URL.Path = path + if oldmatch.Handler != nil { + delete(s.c.Env, web.MatchKey) + } + defer func() { r.URL.Path = oldpath + + if s.c.Env == nil { + return + } + if oldmatch.Handler != nil { + s.c.Env[web.MatchKey] = oldmatch + } else { + delete(s.c.Env, web.MatchKey) + } }() } } diff --git a/web/middleware/subrouter_test.go b/web/middleware/subrouter_test.go new file mode 100644 index 0000000..c46c27e --- /dev/null +++ b/web/middleware/subrouter_test.go @@ -0,0 +1,28 @@ +package middleware + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/zenazn/goji/web" +) + +func TestSubRouterMatch(t *testing.T) { + m := web.New() + m.Use(m.Router) + + m2 := web.New() + m2.Use(SubRouter) + m2.Get("/bar", func(w http.ResponseWriter, r *http.Request) {}) + + m.Get("/foo/*", m2) + + r, err := http.NewRequest("GET", "/foo/bar", nil) + if err != nil { + t.Fatal(err) + } + + // This function will recurse forever if SubRouter + Match didn't work. + m.ServeHTTP(httptest.NewRecorder(), r) +}