背景:
本文实验gin框架下自定义中间件 以日志为例
代码:
package main
import (
"log"
"time"
"github.com/gin-gonic/gin"
)
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
t := time.Now()
// Set example variable
c.Set("example", "12345")
// before request
c.Next()
// after request
latency := time.Since(t)
log.Print(latency)
// access the status we are sending
status := c.Writer.Status()
log.Println(status)
}
}
func main() {
r := gin.New()
r.Use(Logger())
r.GET("/test", func(c *gin.Context) {
example := c.MustGet("example").(string)
// it would print: "12345"
log.Println(example)
})
// Listen and serve on 0.0.0.0:8080
r.Run(":8080")
}
运行效果
2019/12/05 19:35:13 12345
2019/12/05 19:35:13 214.392µs
2019/12/05 19:35:13 200
2019/12/05 19:35:15 12345
2019/12/05 19:35:15 32.252µs
2019/12/05 19:35:15 200