面经-gin中间件/gin路由什么原理

353 阅读1分钟

中间件

  • 洋葱模型:一个请求过来先执行一系列中间件到handerler函数在过一系列中间件,到响应

  • Gin的中间件是通过Use方法设置的

  • 先把handerler加进去切片,然后一层一层剥洋葱

image.png

package main

import "fmt"

type Context struct {
   handlers []func(c *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)
}
//执行next从一层到另一层
func (this *Context)Next()  {
   this.index++
   this.handlers[this.index](this)//剥洋葱 下一层
}
// 执行handler里第一个
func (this *Context)Run()  { //剥洋葱第一次
   this.handlers[0](this)
}
func main()  {
   c := &Context{}
   c.Use(Middleware1())
   c.Use(Middleware2())
   c.GET("/", func(c *Context) {
      fmt.Println("get handler func")
   })
   c.Run()
}


// 中间件1
func Middleware1() func(c *Context) {
   return func(c *Context) {
      fmt.Println("midd1")
      c.Next()//剥洋葱
      fmt.Println("midd1--end")
   }
}

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


midd1
midd2
get handler func
midd2--end
midd1--end

gin路由

  • 采用前缀树的方式实现动态路由

  • 路由:根据不同的 URL 找到对应的处理函数即可