13.6 为gin增加middleware

一、增加middleware

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?