package main import ( "net/http" "strings" "github.com/gin-gonic/gin" ) func main() { r:= gin.New() r.Use(gin.Logger(), gin.Recovery()) r.GET("/", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "hell", }) }) // 处理 404 请求 r.NoRoute(func(c *gin.Context) { acceptString := c.Request.Header.Get("Accept") if strings.Contains(acceptString, "text/html") { c.String(http.StatusNotFound, "页面返回 404, Not Found") }else { c.JSON(http.StatusNotFound, gin.H{ "error_code": 404, "error_message": "404 Not Found", }) } }) r.Run(":8080") }