Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add function to expose allowed methods for use in custom 405-handlers #884

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
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)
}
})
}