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可以不写,也能执行,详细请看

5万+

被折叠的 条评论
为什么被折叠?



