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(),则整个过程会产生嵌套关系。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值