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
Fixes #870
  • Loading branch information
flimzy committed Dec 14, 2023
1 parent 58ca6d6 commit 1fb5fed
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 5 deletions.
21 changes: 17 additions & 4 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,23 @@ func NewRouteContext() *Context {
return &Context{}
}

var (
// RouteCtxKey is the context.Context key to store the request context.
RouteCtxKey = &contextKey{"RouteContext"}
)
// 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
}

// RouteCtxKey is the context.Context key to store the request context.
var RouteCtxKey = &contextKey{"RouteContext"}

// Context is the default routing context set on the root node of a
// request context to track route patterns, URL parameters and
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 1fb5fed

Please sign in to comment.