gin middleware process control: Next(), Abort()

gin middleware process control

Next()

Source code comment: Nextshould 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.....
	*/.

Please add a picture description
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: AbortPrevents 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.

AbortCalled 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 Funcwill 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......

Guess you like

Origin blog.csdn.net/m0_53328239/article/details/131755007