天天看點

gin架構中間件

1. Gin架構中間件

Gin架構中間件

A. Gin架構允許在請求處理過程中,加入使用者自己的鈎子函數。這個鈎子函數就叫中間件

package main
import (
"log"
"time"
"net/http"
"github.com/gin-gonic/gin"
)
func StatCost() gin.HandlerFunc {
return func(c *gin.Context) {
t := time.Now()
//可以設定一些公共參數
c.Set("example", "12345")
//等其他中間件先執行
c.Next()
//擷取耗時
latency := time.Since(t)
log.Print(latency)
}
}
func main() {
r := gin.New()
r.Use(StatCost())
r.GET("/test", func(c *gin.Context) {
example := c.MustGet("example").(string)
// it would print: "12345"
log.Println(example)
c.JSON(http.StatusOK, gin.H{
"message": "success",
})
})
// Listen and serve on 0.0.0.0:8080
r.Run(":8080")
}