Gokang gin 记录 response

背景记录 api 的返回值到日志 方便排查问题

查阅文档

使用Gin 提供方的中间件可以处理

点击查看代码
package main

import (
    "fmt"
    "math"
)

const abortIndex int8 = math.MaxInt8 / 2

type Context struct {
    Handlers []func(*Context)
    index    int8
}

func (c *Context) Next() {
    c.index++
    for c.index < int8(len(c.Handlers)) {
        c.Handlers[c.index](c)
        c.index++
    }
}

func (c *Context) Abort() {
    c.index = abortIndex
}

func main() {
    c := &Context{}
    c.Handlers = make([]func(*Context), 0)

    // 注册中间件
    c.Handlers = append(c.Handlers, h1)
    c.Handlers = append(c.Handlers, h2)
    c.Handlers = append(c.Handlers, h3)

    // 控制器函数
    c.Handlers = append(c.Handlers, actionHandler)

    // 限制handler个数
    if len(c.Handlers) >= int(abortIndex) {
        panic("too many handlers")
    }

    // 启动
    c.Handlers[0](c)
    c.Next()
}

func actionHandler(c *Context) {
    fmt.Println("action handler")
}

func h1(c *Context) {
    fmt.Println("h1 start")
}

func h2(c *Context) {
    fmt.Println("h2 start")
    c.Abort()
    c.Next()
    fmt.Println("h2 end")
}

func h3(c *Context) {
    c.Next()
    fmt.Println("h3 end")
}

直接贴代码

type bodyLogWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

func (w bodyLogWriter) Write(b []byte) (int, error) {
	w.body.Write(b)
	return w.ResponseWriter.Write(b)
}

func ginBodyLogMiddleware(c *gin.Context) {
	blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
	c.Writer = blw
	c.Next()
	statusCode := c.Writer.Status()
	go func(statusCode int) {
		if statusCode == 200 {
			timeTicker := time.NewTicker(time.Second * 2)
			i := 0
			for {
				if i > 5 {
					break
				}

				fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
				i++
				<-timeTicker.C

			}
			// 清理计时器
			timeTicker.Stop()
		}
	}(statusCode)
}
router.Use(ginBodyLogMiddleware)
posted @ 2022-04-13 13:46  vx_guanchaoguo0  阅读(48)  评论(0编辑  收藏  举报