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 58ca6d6 commit 86904e3
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 @@ -130,6 +130,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 @@ -85,3 +88,26 @@ func TestRoutePattern(t *testing.T) {
t.Fatal("unexpected route pattern for root: " + 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 86904e3

Please sign in to comment.