gin 框架中middleware 怎么嵌套调用的

//通过Next函数实现嵌套,举例如下
package main

import "fmt"

type A struct{
index int
handles HandlesFunc
}

func (a *A) Handle(f HandleFunc){
a.handles=append(a.handles,f)
}

func (a* A) Next(){
a.index++ //这个是关键
for i:=len(a.handles);a.index<i;a.index++ {
a.handles[a.index](a)
}
}

type HandleFunc func(a *A)
type HandlesFunc []HandleFunc

func main(){
a:=&A{
index:-1,
handles:make(HandlesFunc,0),
}
a.Handle(func(a* A){fmt.Println("in function 1");a.Next();fmt.Println("exit function 1")})
a.Handle(func(a* A){fmt.Println("in function 2");a.Next();fmt.Println("exit function 2")})
a.Next()
}


//结果如下

in function 1
in function 2
exit function 2
exit function 1

posted @ 2018-03-30 15:07  yyanbiao  阅读(398)  评论(0编辑  收藏  举报