Merge pull request #139 from bign8/issue_20
[feature] NotFoundHandler on Subrouters is now called correctly.
This commit is contained in:
19
mux.go
19
mux.go
@@ -59,6 +59,12 @@ func (r *Router) Match(req *http.Request, match *RouteMatch) bool {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// Closest match for a router (includes sub-routers)
|
||||
if r.NotFoundHandler != nil {
|
||||
match.Handler = r.NotFoundHandler
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -89,10 +95,7 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
setCurrentRoute(req, match.Route)
|
||||
}
|
||||
if handler == nil {
|
||||
handler = r.NotFoundHandler
|
||||
if handler == nil {
|
||||
handler = http.NotFoundHandler()
|
||||
}
|
||||
handler = http.NotFoundHandler()
|
||||
}
|
||||
if !r.KeepContext {
|
||||
defer context.Clear(req)
|
||||
@@ -324,11 +327,15 @@ func CurrentRoute(r *http.Request) *Route {
|
||||
}
|
||||
|
||||
func setVars(r *http.Request, val interface{}) {
|
||||
context.Set(r, varsKey, val)
|
||||
if val != nil {
|
||||
context.Set(r, varsKey, val)
|
||||
}
|
||||
}
|
||||
|
||||
func setCurrentRoute(r *http.Request, val interface{}) {
|
||||
context.Set(r, routeKey, val)
|
||||
if val != nil {
|
||||
context.Set(r, routeKey, val)
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
24
mux_test.go
24
mux_test.go
@@ -1123,6 +1123,30 @@ func TestWalkNested(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubrouterErrorHandling(t *testing.T) {
|
||||
superRouterCalled := false
|
||||
subRouterCalled := false
|
||||
|
||||
router := NewRouter()
|
||||
router.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
superRouterCalled = true
|
||||
})
|
||||
subRouter := router.PathPrefix("/bign8").Subrouter()
|
||||
subRouter.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
subRouterCalled = true
|
||||
})
|
||||
|
||||
req, _ := http.NewRequest("GET", "http://localhost/bign8/was/here", nil)
|
||||
router.ServeHTTP(NewRecorder(), req)
|
||||
|
||||
if superRouterCalled {
|
||||
t.Error("Super router 404 handler called when sub-router 404 handler is available.")
|
||||
}
|
||||
if !subRouterCalled {
|
||||
t.Error("Sub-router 404 handler was not called.")
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user