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
  • Loading branch information
flimzy committed Dec 14, 2023
1 parent 58ca6d6 commit f44bf53
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
15 changes: 15 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,21 @@ func NewRouteContext() *Context {
return &Context{}
}

// WithRouteContext returns the list of methods allowed for the current
// request, based on the current routing context.
func AllowedMethods(ctx context.Context) []string {
if rctx := RouteContext(ctx); rctx != nil {
result := make([]string, 0, len(rctx.methodsAllowed))
for _, method := range rctx.methodsAllowed {
if method := methodTypString(method); method != "" {
result = append(result, method)
}
}
return result
}
return nil
}

var (
// RouteCtxKey is the context.Context key to store the request context.
RouteCtxKey = &contextKey{"RouteContext"}
Expand Down
35 changes: 34 additions & 1 deletion context_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package chi

import "testing"
import (
"context"
"strings"
"testing"
)

// TestRoutePattern tests correct in-the-middle wildcard removals.
// If user organizes a router like this:
Expand Down Expand Up @@ -85,3 +89,32 @@ func TestRoutePattern(t *testing.T) {
t.Fatal("unexpected route pattern for root: " + p)
}
}

func TestAllowedMethods(t *testing.T) {
t.Run("no chi context", func(t *testing.T) {
got := AllowedMethods(context.Background())
if got != nil {
t.Errorf("Unexpected allowed methods: %v", got)
}
})
t.Run("expected methods", func(t *testing.T) {
want := "GET HEAD"
ctx := context.WithValue(context.Background(), RouteCtxKey, &Context{
methodsAllowed: []methodTyp{mGET, mHEAD},
})
got := strings.Join(AllowedMethods(ctx), " ")
if want != got {
t.Errorf("Unexpected allowed methods: %s, want: %s", got, want)
}
})
t.Run("unexpected methods", func(t *testing.T) {
want := "GET HEAD"
ctx := context.WithValue(context.Background(), RouteCtxKey, &Context{
methodsAllowed: []methodTyp{mGET, mHEAD, 9000},
})
got := strings.Join(AllowedMethods(ctx), " ")
if want != got {
t.Errorf("Unexpected allowed methods: %s, want: %s", got, want)
}
})
}

0 comments on commit f44bf53

Please sign in to comment.