0%

gin-框架中间件

gin 框架中间件相关方法:

c.Next()    // 向下执行嵌套方法
c.Abort() // 退出当前执行函数 >>> 例如鉴权失败,不给拿数据...

gin 框架中间件运行逻辑:

package main

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

func func1(c *gin.Context) {
fmt.Println("func1")
}

func func2(c *gin.Context) {
fmt.Println("func2 before")
c.Next()
fmt.Println("func2 after")
}

func func3(c *gin.Context) {
fmt.Println("func3")
}

func func4(c *gin.Context) {
fmt.Println("func4")
func2(c)
fmt.Println("func4 结束")
}

func func5(c *gin.Context) {
fmt.Println("func5")
}

func main() {
r := gin.Default()
r.GET("/hello", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})

shopGroup := r.Group("/shop", func1, func2)

shopGroup.Use(func3)
{
shopGroup.GET("/index", func4, func5)
}

r.Run(":8000")
}

访问 /shop/index 返回打印状态:

func1
func2 before
func3
func4
func2 before
func5
func2 after
func4 结束
func2 after
[GIN] 2024/06/13 - 00:58:14 | 200 | 38.125µs | 127.0.0.1 | GET "/shop/index"

gin 框架中间值的传递>>:

访问:127.0.0.1:8000/shop/index

  • 经过func4 中定义的 name >>> 然后我们在 func5中调用其值
  • 值的注意的是 在1.18版本中 go是需要做类型转换的,但是在 go 1.21 就不需要了,中间有个时间差, 应该是gin框架更新机制
package main

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

func func1(c *gin.Context) {
fmt.Println("func1")
}

func func2(c *gin.Context) {
fmt.Println("func2 before")
c.Next()
fmt.Println("func2 after")
}

func func3(c *gin.Context) {
fmt.Println("func3")
//c.Abort()
}

func func4(c *gin.Context) {
fmt.Println("func4")
c.Set("name", "大头")
}

func func5(c *gin.Context) {
fmt.Println("func5")
v, ok := c.Get("name")
if ok {
fmt.Println(v)
}
// 在 go 1.18 之前 需要做类型转换 但是在1.21 版本中 ,我发现 不用转换,直接打印页没有问题
//if ok {
// vStr := v.(string)
// fmt.Println(vStr)
//}
}

func main() {
r := gin.Default()
r.GET("/hello", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})

shopGroup := r.Group("/shop", func1, func2)
shopGroup.Use(func3)
{
shopGroup.GET("/index", func4, func5)
}
r.Run(":8000")
}

打印结果:

func1
func2 before
func3
func4
func5
大头
func2 after
[GIN] 2024/06/13 - 01:21:15 | 200 | 85.875µs | 127.0.0.1 | GET "/shop/index"