Skip to content

Commit

Permalink
Add function to expose allowed methods for use in custom 405-handlers
Browse files Browse the repository at this point in the history
Fixes #870
  • Loading branch information
flimzy committed Sep 25, 2024
1 parent 882c15e commit 042e19b
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
12 changes: 12 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,18 @@ func (x *Context) RoutePattern() string {
return routePattern
}

// WithRouteContext returns the list of methods allowed for the current
// request, based on the current routing context.
func (x *Context) AllowedMethods() []string {
result := make([]string, 0, len(x.methodsAllowed))
for _, method := range x.methodsAllowed {
if method := methodTypString(method); method != "" {
result = append(result, method)
}
}
return result
}

// replaceWildcards takes a route pattern and recursively replaces all
// occurrences of "/*/" to "/".
func replaceWildcards(p string) string {
Expand Down
28 changes: 27 additions & 1 deletion context_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package chi

import "testing"
import (
"strings"
"testing"
)

// TestRoutePattern tests correct in-the-middle wildcard removals.
// If user organizes a router like this:
Expand Down Expand Up @@ -91,3 +94,26 @@ func TestRoutePattern(t *testing.T) {
t.Fatalf("unexpected non-empty route pattern for nil context: %q", p)
}
}

func TestAllowedMethods(t *testing.T) {
t.Run("expected methods", func(t *testing.T) {
want := "GET HEAD"
rctx := &Context{
methodsAllowed: []methodTyp{mGET, mHEAD},
}
got := strings.Join(rctx.AllowedMethods(), " ")
if want != got {
t.Errorf("Unexpected allowed methods: %s, want: %s", got, want)
}
})
t.Run("unexpected methods", func(t *testing.T) {
want := "GET HEAD"
rctx := &Context{
methodsAllowed: []methodTyp{mGET, mHEAD, 9000},
}
got := strings.Join(rctx.AllowedMethods(), " ")
if want != got {
t.Errorf("Unexpected allowed methods: %s, want: %s", got, want)
}
})
}

0 comments on commit 042e19b

Please sign in to comment.