Method Not Allowed 常见问题
当我使用不支持的 HTTP 方法访问路由时,Gin 返回 404 错误。如何让它返回 405 Method Not Allowed?
在你的 Gin 路由器中配置以下选项 r.HandleMethodNotAllowed = true。这会让 Gin 在路由存在但不支持请求的 HTTP 方法时返回 405 Method Not Allowed 响应:
package mainimport ( "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 AllowedAllow: GETContent-Type: text/plainDate: Sat, 01 Nov 2025 14:49:36 GMTContent-Length: 22
405 method not allowed