如何在Golang中间件中两次读取请求正文? [英] How to read request body twice in Golang middleware?

查看:160
本文介绍了如何在Golang中间件中两次读取请求正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在中间件中,我想读取请求主体以执行一些检查.然后,该请求将传递到下一个中​​间件,在该中间件中将再次读取主体. 这是我的工作:

In a middleware, I want to read request body to perform some checks. Then, the request is passed to the next middleware where the body will be read again. Here's what I do:

bodyBytes, _ := ioutil.ReadAll(req.Body)
req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
// use bodyBytes
// pass to next middleware

现在,req.Body.Close不会执行任何操作.自从以前的req.Body.Close实现执行一些连接处理以来,它会中断吗?

Now, req.Body.Close will do nothing. Will it break since the previous req.Body.Close implementation did some connection handling?

推荐答案

自上次req.Body.Close实现以来,是否会进行一些连接处理?

Will it break since the previous req.Body.Close implementation did some connection handling?

否.

但是您的代码有错误:阅读完所有内容后,您应该关闭req.Body.然后,按照您的方式构造一个新的ReadCloser,并将其交给下一个中间件(该中间件本身或后面的东西负责关闭).

But your code is buggy: You should close the req.Body once you are done reading all of it. Then you construct a new ReadCloser as you did and hand this to the next middleware (which itself or stuff further down is responsible for closing is.)

bodyBytes, _ := ioutil.ReadAll(req.Body)
req.Body.Close()  //  must close
req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))

这篇关于如何在Golang中间件中两次读取请求正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆