Merge pull request #51 from javierprovecho/master
Add support for HTTP 405
diff --git a/router.go b/router.go
index 7716dc7..1028c03 100644
--- a/router.go
+++ b/router.go
@@ -313,6 +313,18 @@
}
}
+ // Handle 405
+ for method, _ := range r.trees {
+ if method == req.Method {
+ continue
+ }
+
+ if handle, _, _ := r.trees[method].getValue(req.URL.Path); handle != nil {
+ http.Error(w, "405 method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ }
+
// Handle 404
if r.NotFound != nil {
r.NotFound(w, req)
diff --git a/router_test.go b/router_test.go
index 7c8ac09..9703908 100644
--- a/router_test.go
+++ b/router_test.go
@@ -165,6 +165,23 @@
}
}
+func TestRouterNotAllowed(t *testing.T) {
+ handlerFunc := func(_ http.ResponseWriter, _ *http.Request, _ Params) {}
+ method := "/method"
+ code := 405
+
+ router := New()
+ router.POST(method, handlerFunc)
+
+ // Test not allowed
+ r, _ := http.NewRequest("GET", method, nil)
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, r)
+ if !(w.Code == code) {
+ t.Errorf("NotAllowed handling route %s failed: Code=%d, Header=%v", w.Code, w.Header())
+ }
+}
+
func TestRouterNotFound(t *testing.T) {
handlerFunc := func(_ http.ResponseWriter, _ *http.Request, _ Params) {}