From bbfc771618c46eca67ccea92f721f8cf14faa503 Mon Sep 17 00:00:00 2001 From: Miguel Serra Date: Tue, 2 Jun 2020 18:10:39 +0100 Subject: [PATCH] Add 405 allow header --- gin.go | 9 ++++++--- routes_test.go | 2 ++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/gin.go b/gin.go index 1e126179..c3efbde1 100644 --- a/gin.go +++ b/gin.go @@ -440,18 +440,18 @@ func (engine *Engine) handleHTTPRequest(c *Context) { } if value := tree.root.getValue(rPath, nil, unescape); value.handlers != nil { c.handlers = engine.allNoMethod - serveError(c, http.StatusMethodNotAllowed, default405Body) + serveError(c, http.StatusMethodNotAllowed, default405Body, &httpMethod) return } } } c.handlers = engine.allNoRoute - serveError(c, http.StatusNotFound, default404Body) + serveError(c, http.StatusNotFound, default404Body, nil) } var mimePlain = []string{MIMEPlain} -func serveError(c *Context, code int, defaultMessage []byte) { +func serveError(c *Context, code int, defaultMessage []byte, allowedMethod *string) { c.writermem.status = code c.Next() if c.writermem.Written() { @@ -459,6 +459,9 @@ func serveError(c *Context, code int, defaultMessage []byte) { } if c.writermem.Status() == code { c.writermem.Header()["Content-Type"] = mimePlain + if allowedMethod != nil { + c.writermem.Header()["Allow"] = []string{*allowedMethod} + } _, err := c.Writer.Write(defaultMessage) if err != nil { debugPrint("cannot write message to writer during serve error: %v", err) diff --git a/routes_test.go b/routes_test.go index 11ff71a6..64842838 100644 --- a/routes_test.go +++ b/routes_test.go @@ -374,12 +374,14 @@ func TestRouteNotAllowedEnabled(t *testing.T) { router.POST("/path", func(c *Context) {}) w := performRequest(router, http.MethodGet, "/path") assert.Equal(t, http.StatusMethodNotAllowed, w.Code) + assert.Equal(t, "GET", w.Result().Header["Allow"][0]) router.NoMethod(func(c *Context) { c.String(http.StatusTeapot, "responseText") }) w = performRequest(router, http.MethodGet, "/path") assert.Equal(t, "responseText", w.Body.String()) + assert.NotContains(t, w.Result().Header, "Allow") assert.Equal(t, http.StatusTeapot, w.Code) }