13.5 gin框架介绍
一、gin-gonic/gin框架
第三方http框架:
gin框架:https://github.com/gin-gonic/gin
日志库:go get -u go.uber.org/zap
middleware的使用
context的使用
// 简单使用
package main
import (
"math/rand"
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func main() {
r := gin.Default()
logger, err := zap.NewProduction()
if err != nil {
panic(err)
}
r.Use(func(c *gin.Context) {
s := time.Now()
c.Next()
// 处理时间,返回码,路径
logger.Info("request",
zap.String("请求地址:", c.Request.URL.Path),
zap.Int("返回码:", c.Writer.Status()),
zap.Duration("处理时间:", time.Now().Sub(s)))
}, func(c *gin.Context) {
// 设置内容
c.Set("requestId", rand.Int())
c.Next()
})
r.GET("/ping", func(c *gin.Context) {
h := gin.H{
"message": "pong",
}
// 判断是否存在
if rid, exists := c.Get("requestId"); exists {
h["requestId"] = rid
}
c.JSON(200, h)
})
r.GET("/hello", func(c *gin.Context) {
c.String(200, "hello")
})
r.Run()
}Last updated
Was this helpful?