GO语言手撸中间件案例

GO语言手撸中间件案例

package main
//自定义中间件案例
//MyContext
import (
	"fmt"
	"math"
)
const abortIndex int8=math.MaxInt8 / 2
type MyContext struct {
	handlers []func(c *MyContext)
	index int8
}

func (this *MyContext) Use(f func(c *MyContext)) {
	this.handlers=append(this.handlers,f)
}
func (this *MyContext) GET(path string,f func(c *MyContext))  {
	this.handlers=append(this.handlers,f)
}
//设置阻止下一个中间件
func (this *MyContext) Abort()  {
	this.index=abortIndex
}
func (this *MyContext) Next()  {
	this.index++
	if this.index<int8(len(this.handlers)){
		this.handlers[this.index](this)
		this.index++
	}
}
func (this *MyContext) Run()  {
	this.handlers[0](this)
}
func main() {
	c:=&MyContext{}
	c.Use(Middleware1())
	c.Use(Middleware2())
	c.Use(Middleware3())
	c.GET("/", func(c *MyContext) {
		fmt.Println("GET handler func")
	})
	c.Run()
}
//中间件1
func Middleware1() func(c *MyContext)  {
	return func(c *MyContext) {
		fmt.Println("midd1")
		c.Next()  //剥洋葱
		fmt.Println("midd1--end")
	}
}
//中间件2
func Middleware2() func(c *MyContext)  {
	return func(c *MyContext) {
		fmt.Println("midd2")
		//c.Abort() //阻止下一个中间件
		c.Next()
		fmt.Println("midd2--end")
	}
}
//中间件3
func Middleware3() func(c *MyContext)  {
	return func(c *MyContext) {
		fmt.Println("midd3")
		c.Next()
		fmt.Println("midd3--end")
	}
}

在gin框架中,c,next可以不写,也能执行,详细请看

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值