gin框架的简单使用

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")
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容