Middleware parsing

Each middleware is independent, and multiple middleware can form a chain structure for pipelining interception and processing of requests.

Except for the built-in middlewarer := gin.Default()Logging middleware inLogger()And recover error scene middlewareRecovery()In addition, you can also customize middleware, such as:

func TimeCostMiddleware(c *gin.Context)  {
	t := time.Now()
	// Before the request
	c.Next() // Process the request
	// After the request
	// Calculate the time of the entire request process
	t2 := time.Since(t)
	log.Println(t2)
}
Copy the code

It can be divided into global middleware and local middleware by type

  • Registered as aGlobal middleware, the use offunc (engine *Engine) Use(middleware ... HandlerFunc), you can also use this function to register routing groups.
package main

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

func main(a) {
   r := gin.Default()
   r.Use(TimeCostMiddleware) // Use global middleware registration
   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()
   // Before the request
   c.Next() // Process the request
   // After the request
   // Calculate the time of the entire request process
   t2 := time.Since(t)
   log.Println("Take", t2)
}
Copy the code
2021/09/01 11:37:33 time-consuming 0 s/GIN 2021/09/01-11:37:33 |? [97;42m 200 ?[0m| 26ms | ::1 |?[97;44m GET ?[0m "/hello"Copy the code
  • Registered as aLocal middlewareWrite directly into function entry parameters, the essence of middlewareHandlerFunc, the route group can also be written to the entry parameter to achieve this effect:
package main

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

func main(a) {
   r := gin.Default()
   r.GET("/hello", TimeCostMiddleware, func(c *gin.Context) { // Register local middleware in the write entry parameter
      c.JSON(http.StatusOK, gin.H{
         "message": "hello",
      })
   })
   _ = r.Run(": 8080")}func TimeCostMiddleware(c *gin.Context)  {
   t := time.Now()
   // Before the request
   c.Next() // Process the request
   // After the request
   // Calculate the time of the entire request process
   t2 := time.Since(t)
   log.Println("Take", t2)
}
Copy the code