main.go 605 B

1234567891011121314151617181920212223242526272829303132333435
  1. package main
  2. import (
  3. "net/http"
  4. "strings"
  5. "github.com/gin-gonic/gin"
  6. )
  7. func main() {
  8. r:= gin.New()
  9. r.Use(gin.Logger(), gin.Recovery())
  10. r.GET("/", func(c *gin.Context) {
  11. c.JSON(http.StatusOK, gin.H{
  12. "message": "hell",
  13. })
  14. })
  15. // 处理 404 请求
  16. r.NoRoute(func(c *gin.Context) {
  17. acceptString := c.Request.Header.Get("Accept")
  18. if strings.Contains(acceptString, "text/html") {
  19. c.String(http.StatusNotFound, "页面返回 404, Not Found")
  20. }else {
  21. c.JSON(http.StatusNotFound, gin.H{
  22. "error_code": 404,
  23. "error_message": "404 Not Found",
  24. })
  25. }
  26. })
  27. r.Run(":8080")
  28. }