Skip to content

Commit 86904e3

Browse files
committed
Add function to expose allowed methods for use in custom 405-handlers
Fixes go-chi#870
1 parent 58ca6d6 commit 86904e3

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
@@ -130,6 +130,18 @@ func (x *Context) RoutePattern() string {
130130
return routePattern
131131
}
132132

133+
// WithRouteContext returns the list of methods allowed for the current
134+
// request, based on the current routing context.
135+
func (x *Context) AllowedMethods() []string {
136+
result := make([]string, 0, len(x.methodsAllowed))
137+
for _, method := range x.methodsAllowed {
138+
if method := methodTypString(method); method != "" {
139+
result = append(result, method)
140+
}
141+
}
142+
return result
143+
}
144+
133145
// replaceWildcards takes a route pattern and recursively replaces all
134146
// occurrences of "/*/" to "/".
135147
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:
@@ -85,3 +88,26 @@ func TestRoutePattern(t *testing.T) {
8588
t.Fatal("unexpected route pattern for root: " + p)
8689
}
8790
}
91+
92+
func TestAllowedMethods(t *testing.T) {
93+
t.Run("expected methods", func(t *testing.T) {
94+
want := "GET HEAD"
95+
rctx := &Context{
96+
methodsAllowed: []methodTyp{mGET, mHEAD},
97+
}
98+
got := strings.Join(rctx.AllowedMethods(), " ")
99+
if want != got {
100+
t.Errorf("Unexpected allowed methods: %s, want: %s", got, want)
101+
}
102+
})
103+
t.Run("unexpected methods", func(t *testing.T) {
104+
want := "GET HEAD"
105+
rctx := &Context{
106+
methodsAllowed: []methodTyp{mGET, mHEAD, 9000},
107+
}
108+
got := strings.Join(rctx.AllowedMethods(), " ")
109+
if want != got {
110+
t.Errorf("Unexpected allowed methods: %s, want: %s", got, want)
111+
}
112+
})
113+
}

0 commit comments

Comments
 (0)