关于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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理