gin Next()使用方法
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
m1 := func(c *gin.Context) {
fmt.Println("m1 start")
//c.Next()会跳过当前中间件后续的逻辑,类似defer,最后再执行c.Next后面的逻辑
//多个c.Next()谁在前面谁后执行,跟defer很像,类似先进后出的栈
c.Next()
fmt.Println("m1 end")
}
m2 := func(c *gin.Context) {
fmt.Println("m2 start")
//该方法会阻止业务逻辑以及该中间件后面中间件执行,但是不会阻止该中间件后面的逻辑执行包括c.Next()
//c.Abort()
c.Next()
fmt.Println("m2 end")
}
m3 := func(c *gin.Context) {
fmt.Println("m3 start")
c.Next()
fmt.Println("m3 end")
}
r.Use(m1, m2, m3)
r.GET("/", func(context *gin.Context) {
context.Next()
context.JSON(http.StatusOK, gin.H{
"message": "demo",
})
fmt.Println("hello world!!")
})
r.Run(":8081")
}
命令行输出
[GIN-debug] Listening and serving HTTP on :8081
m1 start
m2 start
m3 start
hello world!!
m3 end
m2 end
m1 end
[GIN] 2021/03/26 - 12:40:40 |?[97;42m 200 ?[0m| 1.5781ms | 127.0.0.1 |?[97;44m GET ?[0m "/"
|
请发表评论