🦫

Gin で 405 NotAllowed を返す

2025/01/16に公開

Gin で 405 を返す方法

Gin はデフォルトでは 405 を返さない。
https://github.com/gin-gonic/gin/blob/3f818c3fa69e03feb46d2b49d2a8084c425cbed6/gin.go#L204

405 を有効にするためには HandleMethodNotAllowedtrue にする必要があります。

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 でハンドラを登録する必要がある。
https://github.com/gin-gonic/gin/blob/3f818c3fa69e03feb46d2b49d2a8084c425cbed6/gin.go#L308-L313

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"%

参考

https://gabnotes.org/gin-method-not-allowed/

Discussion