跳转到内容

Method Not Allowed 常见问题

当我使用不支持的 HTTP 方法访问路由时,Gin 返回 404 错误。如何让它返回 405 Method Not Allowed?

在你的 Gin 路由器中配置以下选项 r.HandleMethodNotAllowed = true。这会让 Gin 在路由存在但不支持请求的 HTTP 方法时返回 405 Method Not Allowed 响应:

package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.HandleMethodNotAllowed = true
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // 监听并在 0.0.0.0:8080 上服务
}
$ curl -X POST localhost:8000/ping
HTTP/1.1 405 Method Not Allowed
Allow: GET
Content-Type: text/plain
Date: Sat, 01 Nov 2025 14:49:36 GMT
Content-Length: 22
405 method not allowed