Gin洋葱模型

此开源图书由ithaiq原创,创作不易转载请注明出处

Gin是go web领域非常出名的框架,里面源码也值得一读。gin有一个非常出名的洋葱模型,主要在中间件上使用,很巧妙也很值得借鉴,这里模拟gin实现一个简易版的洋葱模型

const abortIndex int8 = math.MaxInt8 / 2

type Context struct {
	handlers []func(ctx *Context)
	index    int8
}

func (this *Context) Use(f func(c *Context)) {
	this.handlers = append(this.handlers, f)
}
func (this *Context) GET(path string, f func(c *Context)) {
	this.handlers = append(this.handlers, f)
}
func (this *Context) Next() {
	this.index++
	if this.index < int8(len(this.handlers)) {
		this.handlers[this.index](this)
		this.index++
	}
}

func (this *Context) Abort() {
	this.index = abortIndex
}
func (this *Context) Run() {
	this.handlers[0](this)
}

func main() {
	c := &Context{}
	c.Use(Middleware1())
	c.Use(Middleware2())
	c.Use(Middleware3())
	c.GET("/", func(c *Context) {
		fmt.Println("handler func")
	})
	c.Run()
}

func Middleware1() func(c *Context) {
	return func(c *Context) {
		fmt.Println("mid1")
		c.Next()
		fmt.Println("mid1 - end")
	}
}

func Middleware2() func(c *Context) {
	return func(c *Context) {
		fmt.Println("mid2")
		c.Next()
		fmt.Println("mid2 - end")
	}
}

func Middleware3() func(c *Context) {
	return func(c *Context) {
		fmt.Println("mid3")
		c.Next()
		fmt.Println("mid3 - end")
	}
}

最后更新于

这有帮助吗?