gin middleware process control
Next()
Source code comment: Next
should only be used inside middleware. It executes pending handlers in the inner chain of call handlers.
In layman's terms, it is the release of middleware. When a middleware code is executed Next()
, the function after it will be executed first, and finally this function will be executed.
eg:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
func m1(c *gin.Context) {
fmt.Println("m1 in......")
c.Next()
fmt.Println("m1 out......")
}
func indexHandler(c *gin.Context) {
fmt.Println("index....in")
c.JSON(http.StatusOK, gin.H{
"msg": "index"})
c.Next()
fmt.Println("index....out")
}
func m2(c *gin.Context) {
fmt.Println("m2 in......")
c.Next()
fmt.Println("m2 out.....")
}
func main() {
router := gin.Default()
router.GET("/", m1, indexHandler, m2)
router.Run(":8080")
}
//输出
/*
m1 in......
index....in
m2 in......
m2 out.....
index....out
m1 out.....
*/.
If one of the middleware responds to c.Abort(), the subsequent middleware will no longer be executed, and all the response middleware will be completed in order
Abort
Source code comment: Abort
Prevents calls to pending handlers. Note that this does not stop the current handler.
Let's say you have an authorization middleware that verifies if the current request is authorized.
Abort
Called to ensure that the rest of the handlers for this request are not called if authorization fails (eg: password mismatch) .
It means that when the program is executed Abort()
, the subsequent ones Handler Func
will not be executed.
eg:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
func m1(c *gin.Context) {
fmt.Println("m1 in......")
c.JSON(http.StatusOK, gin.H{
"msg": "第一个中间件拦截了"})
c.Abort()
}
func indexHandler(c *gin.Context) {
fmt.Println("index....")
c.JSON(http.StatusOK, gin.H{
"msg": "index"})
}
func m2(c *gin.Context) {
fmt.Println("m2 in......")
}
func main() {
router := gin.Default()
router.GET("/", m1, indexHandler, m2)
router.Run(":8080")
}
//输出
//m1 in......