Browse Source

middleware: Make SubRouter Match-aware

This helps avoid a gotcha when using matches with sub-routers.

Fixes #120.
Carl Jackson 11 years ago
parent
commit
ff41f8eaa2
2 changed files with 42 additions and 0 deletions
  1. +14
    -0
      web/middleware/subrouter.go
  2. +28
    -0
      web/middleware/subrouter_test.go

+ 14
- 0
web/middleware/subrouter.go View File

@ -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)
}
}()
}
}


+ 28
- 0
web/middleware/subrouter_test.go View File

@ -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)
}

Loading…
Cancel
Save