4
  • 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

LiberHome
409 声望1.1k 粉丝

有问题 欢迎发邮件 📩 liberhome@163.com