Skip to content

Commit 042e19b

Browse files
committed
Add function to expose allowed methods for use in custom 405-handlers
Fixes go-chi#870
1 parent 882c15e commit 042e19b

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

Diff for: context.go

+12
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,18 @@ func (x *Context) RoutePattern() string {
133133
return routePattern
134134
}
135135

136+
// WithRouteContext returns the list of methods allowed for the current
137+
// request, based on the current routing context.
138+
func (x *Context) AllowedMethods() []string {
139+
result := make([]string, 0, len(x.methodsAllowed))
140+
for _, method := range x.methodsAllowed {
141+
if method := methodTypString(method); method != "" {
142+
result = append(result, method)
143+
}
144+
}
145+
return result
146+
}
147+
136148
// replaceWildcards takes a route pattern and recursively replaces all
137149
// occurrences of "/*/" to "/".
138150
func replaceWildcards(p string) string {

Diff for: context_test.go

+27-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package chi
22

3-
import "testing"
3+
import (
4+
"strings"
5+
"testing"
6+
)
47

58
// TestRoutePattern tests correct in-the-middle wildcard removals.
69
// If user organizes a router like this:
@@ -91,3 +94,26 @@ func TestRoutePattern(t *testing.T) {
9194
t.Fatalf("unexpected non-empty route pattern for nil context: %q", p)
9295
}
9396
}
97+
98+
func TestAllowedMethods(t *testing.T) {
99+
t.Run("expected methods", func(t *testing.T) {
100+
want := "GET HEAD"
101+
rctx := &Context{
102+
methodsAllowed: []methodTyp{mGET, mHEAD},
103+
}
104+
got := strings.Join(rctx.AllowedMethods(), " ")
105+
if want != got {
106+
t.Errorf("Unexpected allowed methods: %s, want: %s", got, want)
107+
}
108+
})
109+
t.Run("unexpected methods", func(t *testing.T) {
110+
want := "GET HEAD"
111+
rctx := &Context{
112+
methodsAllowed: []methodTyp{mGET, mHEAD, 9000},
113+
}
114+
got := strings.Join(rctx.AllowedMethods(), " ")
115+
if want != got {
116+
t.Errorf("Unexpected allowed methods: %s, want: %s", got, want)
117+
}
118+
})
119+
}

0 commit comments

Comments
 (0)