Add 405 allow header

This commit is contained in:
Miguel Serra 2020-06-02 18:10:39 +01:00
parent 5e40c1d49c
commit bbfc771618
2 changed files with 8 additions and 3 deletions

9
gin.go
View File

@ -440,18 +440,18 @@ func (engine *Engine) handleHTTPRequest(c *Context) {
} }
if value := tree.root.getValue(rPath, nil, unescape); value.handlers != nil { if value := tree.root.getValue(rPath, nil, unescape); value.handlers != nil {
c.handlers = engine.allNoMethod c.handlers = engine.allNoMethod
serveError(c, http.StatusMethodNotAllowed, default405Body) serveError(c, http.StatusMethodNotAllowed, default405Body, &httpMethod)
return return
} }
} }
} }
c.handlers = engine.allNoRoute c.handlers = engine.allNoRoute
serveError(c, http.StatusNotFound, default404Body) serveError(c, http.StatusNotFound, default404Body, nil)
} }
var mimePlain = []string{MIMEPlain} 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.writermem.status = code
c.Next() c.Next()
if c.writermem.Written() { if c.writermem.Written() {
@ -459,6 +459,9 @@ func serveError(c *Context, code int, defaultMessage []byte) {
} }
if c.writermem.Status() == code { if c.writermem.Status() == code {
c.writermem.Header()["Content-Type"] = mimePlain c.writermem.Header()["Content-Type"] = mimePlain
if allowedMethod != nil {
c.writermem.Header()["Allow"] = []string{*allowedMethod}
}
_, err := c.Writer.Write(defaultMessage) _, err := c.Writer.Write(defaultMessage)
if err != nil { if err != nil {
debugPrint("cannot write message to writer during serve error: %v", err) debugPrint("cannot write message to writer during serve error: %v", err)

View File

@ -374,12 +374,14 @@ func TestRouteNotAllowedEnabled(t *testing.T) {
router.POST("/path", func(c *Context) {}) router.POST("/path", func(c *Context) {})
w := performRequest(router, http.MethodGet, "/path") w := performRequest(router, http.MethodGet, "/path")
assert.Equal(t, http.StatusMethodNotAllowed, w.Code) assert.Equal(t, http.StatusMethodNotAllowed, w.Code)
assert.Equal(t, "GET", w.Result().Header["Allow"][0])
router.NoMethod(func(c *Context) { router.NoMethod(func(c *Context) {
c.String(http.StatusTeapot, "responseText") c.String(http.StatusTeapot, "responseText")
}) })
w = performRequest(router, http.MethodGet, "/path") w = performRequest(router, http.MethodGet, "/path")
assert.Equal(t, "responseText", w.Body.String()) assert.Equal(t, "responseText", w.Body.String())
assert.NotContains(t, w.Result().Header, "Allow")
assert.Equal(t, http.StatusTeapot, w.Code) assert.Equal(t, http.StatusTeapot, w.Code)
} }