Golang Gin框架 涉及到的context和middleware的使用示例
用到的库:
go get -u go.uber.org/zap
go get -u github.com/gin-gonic/gin
地址:
https://pkg.go.dev/go.uber.org/zap (zap:Package zap provides fast, structured, leveled logging.)
https://github.com/gin-gonic/gin
package main
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"math/rand"
"time"
)
const keyReqId = "requestId"
func main() {
r := gin.Default()
// _ 暂不处理err
logger, _ := zap.NewProduction()
// func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes
// middleware的使用
r.Use(func(c *gin.Context){
s := time.Now()
// 利用r.Use 写日志内容 包括: log latency, response code, path
c.Next()
logger.Info("incoming status", zap.String("path", c.Request.URL.Path),
zap.Int("path", c.Writer.Status()),
zap.Duration("elapsed:", time.Now().Sub(s)))
},func(c *gin.Context){
// context的使用:set一个reqId
c.Set(keyReqId, rand.Int())
c.Next()
})
// 插入一个requestId
r.GET("/ping", func(c *gin.Context) {
hs := gin.H{
"message": "pong",
}
if rid, exist := c.Get(keyReqId); exist {
hs[keyReqId] = rid
}
c.JSON(200, hs)
})
r.GET("/hello", func(c *gin.Context) {
c.String(200, "hello")
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
网友评论