From 578e5664750bf3973a9170a76ca9f1301e6940a2 Mon Sep 17 00:00:00 2001 From: Fenny <25108519+Fenny@users.noreply.github.com> Date: Sun, 21 Jun 2020 12:17:22 +0200 Subject: [PATCH] Add 405 Support --- router_test.go | 9 ++++++--- utils.go | 11 +++++++++-- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/router_test.go b/router_test.go index 66994f40..b677ecfd 100644 --- a/router_test.go +++ b/router_test.go @@ -199,12 +199,14 @@ func registerDummyRoutes(app *App) { } } -// go test -v -run=^$ -bench=Benchmark_App_Benchmark_App_MethodNotAllowed -benchmem -count=4 +// go test -v -run=^$ -bench=Benchmark_App_MethodNotAllowed -benchmem -count=4 func Benchmark_App_MethodNotAllowed(b *testing.B) { app := New() - app.Get("/this/is/a/dummy/route/oke", func(c *Ctx) { + h := func(c *Ctx) { c.Send("Hello World!") - }) + } + app.All("/this/is/a/", h) + app.Get("/this/is/a/dummy/route/oke", h) c := &fasthttp.RequestCtx{} c.Request.Header.SetMethod("DELETE") @@ -215,6 +217,7 @@ func Benchmark_App_MethodNotAllowed(b *testing.B) { } utils.AssertEqual(b, 405, c.Response.StatusCode()) utils.AssertEqual(b, "GET, HEAD", string(c.Response.Header.Peek("Allow"))) + utils.AssertEqual(b, "Cannot DELETE /this/is/a/dummy/route/oke", string(c.Response.Body())) } // go test -v ./... -run=^$ -bench=Benchmark_Router_NotFound -benchmem -count=4 diff --git a/utils.go b/utils.go index 695b0899..60c8b100 100644 --- a/utils.go +++ b/utils.go @@ -17,7 +17,8 @@ import ( // Scan stack if other methods match func setMethodNotAllowed(ctx *Ctx) { - original := methodINT[utils.GetString(ctx.Fasthttp.Request.Header.Method())] + var allow bool + original := methodINT[ctx.method] for i := 0; i < len(intMethod); i++ { // Skip original method if original == i { @@ -39,13 +40,19 @@ func setMethodNotAllowed(ctx *Ctx) { match, _ := route.match(ctx.path, ctx.pathOriginal) // No match, next route if match { - ctx.SendStatus(StatusMethodNotAllowed) + // Update allow bool + allow = true + // Add method to Allow header ctx.Append(HeaderAllow, intMethod[i]) // Break stack loop break } } } + // Update response status + if allow { + ctx.Status(StatusMethodNotAllowed) + } } // Generate and set ETag header to response