中间件解析

每个中间件是独立的,可以多个中间件组成一个链状的结构,让request请求流水线般的进行拦截处理。

Gin框架运行过程图.png

r := gin.Default()Logger()Recovery()
func TimeCostMiddleware(c *gin.Context)  {
	t := time.Now()
	//请求之前
	c.Next() //处理请求
	//请求之后
	//计算整个请求过程耗时
	t2 := time.Since(t)
	log.Println(t2)
}

按类型分为全局中间件和局部中间件

package main

import (
   "github.com/gin-gonic/gin"
   "log"
   "net/http"
   "time"
)

func main() {
   r := gin.Default()
   r.Use(TimeCostMiddleware) //使用Use进行全局中间件的注册
   r.GET("/hello", func(c *gin.Context) {
      c.JSON(http.StatusOK, gin.H{
         "message": "hello",
      })
   })
   _ = r.Run(":8080")
}
func TimeCostMiddleware(c *gin.Context)  {
   t := time.Now()
   //请求之前
   c.Next() //处理请求
   //请求之后
   //计算整个请求过程耗时
   t2 := time.Since(t)
   log.Println("耗时", t2)
}
2021/09/01 11:37:33 耗时 0s
[GIN] 2021/09/01 - 11:37:33 |?[97;42m 200 ?[0m|          26ms |             ::1 |?[97;44m GET     ?[0m "/hello"
package main

import (
   "github.com/gin-gonic/gin"
   "log"
   "net/http"
   "time"
)

func main() {
   r := gin.Default()
   r.GET("/hello", TimeCostMiddleware, func(c *gin.Context) { //写入入口参数中进行局部中间件的注册
      c.JSON(http.StatusOK, gin.H{
         "message": "hello",
      })
   })
   _ = r.Run(":8080")
}
func TimeCostMiddleware(c *gin.Context)  {
   t := time.Now()
   //请求之前
   c.Next() //处理请求
   //请求之后
   //计算整个请求过程耗时
   t2 := time.Since(t)
   log.Println("耗时", t2)
}