gin中间件中使用Next()和Abort()

Next()

Next should be used only inside middleware.
Next应该在中间件中使用
It executes the pending handlers in the chain inside the calling handler.
在调用的handler 中,执行链路上等待的handlers

Abort

Abort prevents pending handlers from being called. Note that this will not stop the current handler.
Abort 阻止等待的handlers被调用. 注意: 这不会停止当前handler
Let’s say you have an authorization middleware that validates that the current request is authorized.
假设您有一个验证当前请求是否已授权的授权中间件。
If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers for this request are not called.
如果授权失败(例如:密码不匹配),则调用Abort以确保不调用此请求的其余处理程序。

代码示例

package main

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

func main(){
    
    
	router := gin.New()

	mid1 := func(c * gin.Context){
    
    
		fmt.Println("mid1 start")
		c.Next()
		fmt.Println("mid1 end")
	}
	mid2 := func(c * gin.Context){
    
    
		fmt.Println("mid2 start")
		//c.Abort()
		c.Next()
		fmt.Println("mid2 end")
	}
	mid3 := func(c * gin.Context){
    
    
		fmt.Println("mid3 start")
		c.Next()
		fmt.Println("mid3 end")
	}
	router.Use(mid1,mid2,mid3)
	router.GET("/",func(c * gin.Context){
    
    
		fmt.Println("process get request")
		c.JSON(http.StatusOK,gin.H{
    
    
			"msg": "hello",
		})
	})
	router.Run()
}

输出

mid1 start
mid2 start
mid3 start
process get request
mid3 end
mid2 end
mid1 end

当某个中间件调用了c.Next(),则整个过程会产生嵌套关系。

猜你喜欢

转载自blog.csdn.net/weixin_45867397/article/details/120602605