参考:https://learnku.com/articles/66234
参考:https://blog.dianduidian.com/post/gin-%E4%B8%AD%E9%97%B4%E4%BB%B6next%E6%96%B9%E6%B3%95%E5%8E%9F%E7%90%86%E8%A7%A3%E6%9E%90/
c.handlers[c.index](c)
执行的时候可能会变,所以虽然在中间件中有调用next函数,但是中间价并不会重复执行c.index = abortIndex
package main
import (
"encoding/json"
"fmt"
)
/**** 上下文
*/
// Context 上下文
type Context struct {
Keys map[string]interface{}
handles HandleChain
index int
}
type HandleChain []func(ctx *Context)
func (c *Context) Render(resultCode int, data interface{}) {
d, _ := json.Marshal(data)
fmt.Println("resultCode:", resultCode, " , data:", string(d))
}
func (c *Context) Next() {
c.index++
for c.index < len(c.handles) {
c.handles[c.index](c)
c.index++
}
}
func (c *Context) reset() {
c.index = -1
}
/** 路由
*/
// router 路由
type router struct {
Handlers map[string]HandleChain
}
type Group struct {
Handles HandleChain
}
func (r *router) RegisterRoute(url string, f func(*Context), group Group) () {
if r.Handlers == nil {
r.Handlers = make(map[string]HandleChain)
}
r.Handlers[url] = append(r.Handlers[url], group.Handles...)
r.Handlers[url] = append(r.Handlers[url], f)
}
func (g *Group) Use(f func(*Context)) {
g.Handles = append(g.Handles, f)
}
func (r *router) Run(url string, c *Context) () {
c.handles = r.Handlers[url]
c.reset()
c.Next()
}
/** 业务代码
*/
// PlusController 加法
func PlusController(c *Context) {
a := c.Keys["a"].(int)
b := c.Keys["b"].(int)
c.Render(200, plus(a, b))
}
// plus 加法函数
func plus(a, b int) int {
return a + b
}
// MultiController 乘法
func MultiController(c *Context) {
a := c.Keys["a"].(int)
b := c.Keys["b"].(int)
c.Render(200, multi(a, b))
}
// multi 加法函数
func multi(a, b int) int {
return a * b
}
/** 主函数
*/
func main() {
r := router{}
group1 := Group{Handles: HandleChain{
func(ctx *Context) {
fmt.Println("testMiddle1")
},
func(ctx *Context) {
ctx.Next()
fmt.Println("testMiddle2")
},
}}
group2 := Group{Handles: HandleChain{
func(ctx *Context) {
fmt.Println("testMiddle3")
ctx.Next()
fmt.Println("testMiddle4")
},
}}
r.RegisterRoute("*", MultiController,group1)
r.RegisterRoute("+", PlusController,group2)
fmt.Println("----------")
r.Run("*", &Context{Keys: map[string]interface{}{"a": 34, "b": 245}})
fmt.Println("----------")
r.Run("+", &Context{Keys: map[string]interface{}{"a": 34, "b": 245}})
}