Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,12 @@ func (mx *Mux) updateRouteHandler() {
// methods for the route.
func methodNotAllowedHandler(methodsAllowed ...methodTyp) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
seen := make(map[string]bool)
for _, m := range methodsAllowed {
if seen[reverseMethodMap[m]] {
continue
}
seen[reverseMethodMap[m]] = true
w.Header().Add("Allow", reverseMethodMap[m])
}
w.WriteHeader(405)
Expand Down
48 changes: 48 additions & 0 deletions mux_test_405_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package chi

import (
"net/http"
"net/http/httptest"
"testing"
)

func TestMethodNotAllowedDeduplication(t *testing.T) {
r := NewRouter()
r.Post("/article/1-2-3", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
r.Post("/article/{a}", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
r.Post("/article/{b}-{c}", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
r.Post("/article/{b}-{c}-{d}", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})

ts := httptest.NewServer(r)
defer ts.Close()

resp, err := http.Get(ts.URL + "/article/1-2-3")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()

if resp.StatusCode != 405 {
t.Errorf("expected 405, got %d", resp.StatusCode)
}

allow := resp.Header["Allow"]
// Count POST occurrences
count := 0
for _, v := range allow {
if v == "POST" {
count++
}
}
if count > 1 {
t.Errorf("Allow header has duplicate POST: %v (count=%d)", allow, count)
}
}