乐趣区

关于go:基于Gin框架的web后端开发九-Gin框架的路由和路由组

  • tips: 如果用浏览器测试的时候呈现之前几篇博客编码的后果,能够删除一下 cookie,或者关上无痕模式。

个别的路由能够这么写:

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

func main() {r := gin.Default()
    // 拜访 /index 的 GET 申请,走这条路
    r.GET("/index", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"mathod": "GET",})
    })
    r.POST("/index", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"method": "POST",})
    })
    r.DELETE("/index", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"method": "DELETE",})
    })
    r.PUT("/index", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"method": "PUT",})
    })
    // 能够解决所有申请
    r.Any("/index", func(c *gin.Context) {
        switch c.Request.Method {
        case http.MethodGet:
            c.JSON(http.StatusOK, gin.H{"method": "GET"})
        case http.MethodPost:
            c.JSON(http.StatusOK, gin.H{"method": "POST"})
        }
        c.JSON(http.StatusOK, gin.H{"method": "ANY",})
    })
    r.NoRoute(func(c *gin.Context) {c.JSON(http.StatusNotFound, gin.H{"msg": "there is no such site, you may interested in https://segmentfault.com/u/liberhome"})
    })
    r.Run(":9090")
}

路由组能够这么写:

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

func main() {r := gin.Default()
    // 把共有的前缀提出来
    videoGroup := r.Group("/video")
    {videoGroup.GET("/index", func(c *gin.Context) {
            c.JSON(http.StatusOK, gin.H{"mathod": "GET",})
        })
        videoGroup.POST("/index", func(c *gin.Context) {
            c.JSON(http.StatusOK, gin.H{"method": "POST",})
        })
        videoGroup.DELETE("/index", func(c *gin.Context) {
            c.JSON(http.StatusOK, gin.H{"method": "DELETE",})
        })
        videoGroup.PUT("/index", func(c *gin.Context) {
            c.JSON(http.StatusOK, gin.H{"method": "PUT",})
        })
        // 能够解决所有申请
        videoGroup.Any("/index", func(c *gin.Context) {
            switch c.Request.Method {
            case http.MethodGet:
                c.JSON(http.StatusOK, gin.H{"method": "GET"})
            case http.MethodPost:
                c.JSON(http.StatusOK, gin.H{"method": "POST"})
            }
            c.JSON(http.StatusOK, gin.H{"method": "ANY",})
        })
    }
    r.Run(":9090")
}

另外,路由组反对嵌套,在划分 API 层级 or 业务逻辑的时候罕用。


参考:bilibili

退出移动版