Content

gin自定义中间件解决requestBody不可重复读问题(最新推荐)(egg中间件)深度揭秘

文章摘要

这篇文章展示了如何在Gin框架中注册中间件,以优化body读取过程。通过重写`GetBody`方法,代码使得每次调用时都可以复用缓存的数据,避免频繁初始化。具体来说,文章提到使用`r.Use`注册中间件,读取body内容后将其缓存,避免了每次读取时初始化`io.ReadCloser`,从而提升了性能。

r :=gin.Default() // 注册中间件,使body可以重复读取 r.Use(func(context *gin.Context) { all, err :=context.GetRawData() // 读取body的内容 if err !=nil { log.Fatal(err) } // 重写 GetBody 方法,以便后续的其他操作 context.Request.GetBody=func() (io.ReadCloser, error) { context.Request.Body=io.NopCloser(bytes.NewBuffer(all)) buffer :=bytes.NewBuffer(all) closer :=io.NopCloser(buffer) return closer, nil } body, _ :=context.Request.GetBody() // 每次调用GetBody方法,都会新生成一个io.ReadCloser,但是底层的byte数据,都是all变量缓存的。 context.Request.Body=body context.Next() })