r:=gin.Default()
// 定义一个logger
logger,err:=zap.NewProduction()
if err!=nil{
panic(err)
}
r.Use(func(c *gin.Context) {
s:=time.Now()
c.Next()
logger.Info("incoming request",
// zap 打印日志路径 状态 以及耗时
zap.String("path",c.Request.URL.Path),
zap.Int("status",c.Writer.Status()),
zap.Duration("elapsed",time.Now().Sub(s)),
)
}, func(c *gin.Context) {
//设置一个requestID 下文使用
c.Set("requestId",rand.Int())
c.Next()
},
)
r.GET("/ping", func(c *gin.Context) {
h:=gin.H{
"message":"pong",
}
// 判断有无requestID 有的话写入json 数据种
if rid,exists:=c.Get("requestId");exists {
h["requestId"]=rid
}
c.JSON(200,h)
})
r.GET("/hello", func(c *gin.Context) {
c.JSON(200, gin.H{
"hello":"aa",
})
})
r.Run(":8080")
gin 和zap 搭建一个简单的http server
最新推荐文章于 2024-05-26 17:23:18 发布