@@ -392,6 +392,43 @@ func TestMuxNestedNotFound(t *testing.T) {
392392 }
393393}
394394
395+ func TestMethodNotAllowed (t * testing.T ) {
396+ r := NewRouter ()
397+
398+ r .Get ("/hi" , func (w http.ResponseWriter , r * http.Request ) {
399+ w .Write ([]byte ("hi, get" ))
400+ })
401+
402+ r .Head ("/hi" , func (w http.ResponseWriter , r * http.Request ) {
403+ w .Write ([]byte ("hi, head" ))
404+ })
405+
406+ ts := httptest .NewServer (r )
407+ defer ts .Close ()
408+
409+ t .Run ("Registered Method" , func (t * testing.T ) {
410+ resp , _ := testRequest (t , ts , "GET" , "/hi" , nil )
411+ if resp .StatusCode != 200 {
412+ t .Fatal (resp .Status )
413+ }
414+ if resp .Header .Values ("Allow" ) != nil {
415+ t .Fatal ("allow should be empty when method is registered" )
416+ }
417+ })
418+
419+ t .Run ("Unregistered Method" , func (t * testing.T ) {
420+ resp , _ := testRequest (t , ts , "POST" , "/hi" , nil )
421+ if resp .StatusCode != 405 {
422+ t .Fatal (resp .Status )
423+ }
424+ allowedMethods := resp .Header .Values ("Allow" )
425+ if len (allowedMethods ) != 2 || allowedMethods [0 ] != "GET" || allowedMethods [1 ] != "HEAD" {
426+ t .Fatal ("Allow header should contain 2 headers: GET, HEAD. Received: " , allowedMethods )
427+
428+ }
429+ })
430+ }
431+
395432func TestMuxNestedMethodNotAllowed (t * testing.T ) {
396433 r := NewRouter ()
397434 r .Get ("/root" , func (w http.ResponseWriter , r * http.Request ) {
@@ -1771,6 +1808,7 @@ func BenchmarkMux(b *testing.B) {
17711808 mx := NewRouter ()
17721809 mx .Get ("/" , h1 )
17731810 mx .Get ("/hi" , h2 )
1811+ mx .Post ("/hi-post" , h2 ) // used to benchmark 405 responses
17741812 mx .Get ("/sup/{id}/and/{this}" , h3 )
17751813 mx .Get ("/sup/{id}/{bar:foo}/{this}" , h3 )
17761814
@@ -1787,6 +1825,7 @@ func BenchmarkMux(b *testing.B) {
17871825 routes := []string {
17881826 "/" ,
17891827 "/hi" ,
1828+ "/hi-post" ,
17901829 "/sup/123/and/this" ,
17911830 "/sup/123/foo/this" ,
17921831 "/sharing/z/aBc" , // subrouter-1
0 commit comments