From 86904e3a65e111b654fc82ee91ffe5de7b59a140 Mon Sep 17 00:00:00 2001 From: Jonathan Hall Date: Thu, 14 Dec 2023 12:06:08 +0100 Subject: [PATCH] Add function to expose allowed methods for use in custom 405-handlers Fixes #870 --- context.go | 12 ++++++++++++ context_test.go | 28 +++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index 21b1384e..8c2ee171 100644 --- a/context.go +++ b/context.go @@ -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 { diff --git a/context_test.go b/context_test.go index 4731c709..e8da4285 100644 --- a/context_test.go +++ b/context_test.go @@ -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: @@ -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) + } + }) +}