🦫
Gin で 405 NotAllowed を返す
Gin で 405 を返す方法
Gin はデフォルトでは 405 を返さない。
405 を有効にするためには HandleMethodNotAllowed
を true
にする必要があります。
func main() {
r := gin.Default()
r.HandleMethodNotAllowed = true
r.GET("/example", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "example",
})
})
r.POST("/example", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "example",
})
})
r.Run("localhost:7777")
}
許可されていない PUT
のレスポンス結果
❯ curl -i -X PUT http://localhost:7777/example
HTTP/1.1 405 Method Not Allowed
Allow: GET, POST
Content-Type: text/plain
Date: hogehoge
Content-Length: 22
405 method not allowed%
レスポンスボディをデフォルトから変更したい
また、レスポンスボディをデフォルトから変更したい場合は NoMethod
でハンドラを登録する必要がある。
func main() {
r := gin.Default()
r.HandleMethodNotAllowed = true
+ r.NoMethod(func(c *gin.Context) {
+ c.JSON(http.StatusMethodNotAllowed, "Custom error message.")
+ })
r.GET("/example", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "example",
})
})
r.POST("/example", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "example",
})
})
r.Run("localhost:7777")
}
許可されていない PUT
のレスポンス結果
❯ curl -i -X PUT http://localhost:7777/example
HTTP/1.1 405 Method Not Allowed
Allow: GET, POST
Content-Type: application/json; charset=utf-8
Date: hogehoge
Content-Length: 22
"Custom error message"%
参考
Discussion