英文:
'json body could not be decoded: EOF' after trying to read the request body
问题
我写了一个记录中间件,用于存储传入的GraphQL请求信息。问题是,如果我尝试读取请求体,我会收到以下400 Bad Request错误:
{
"errors": [
{
"message": "无法解码JSON主体:EOF"
}
],
"data": null
}
我的代码:
clonedReq := r.Clone(ctx)
data, _ := io.ReadAll(clonedReq.Body)
// 存储数据...
fmt.Println(string(data))
数据被显示出来,但之后我遇到了EOF错误。如果我注释掉这部分代码,请求就可以正常响应。
无论是否使用Clone
对请求进行深拷贝,问题仍然存在。
英文:
I've written a logger middleware which stores incoming GraphQL requests info. The problem is if I try to read the request body, I get the following 400 Bad Request:
{
"errors": [
{
"message": "json body could not be decoded: EOF"
}
],
"data": null
}
My code:
clonedReq := r.Clone(ctx)
data, _ := io.ReadAll(clonedReq.Body)
// store the data...
fmt.Println(string(data))
The data is displayed, but then I face the EOF error. If I comment this part out, the request is responded without any problems.
With or without a deep copy of the request with Clone
, the issue persists.
答案1
得分: 3
中间件读取请求体直到EOF。处理程序遇到EOF。请求体的内容在Clone()中没有被克隆。
为了修复代码,在中间件中恢复请求体:
data, _ := io.ReadAll(r.Body)
r.Body = io.NopCloser(bytes.NewReader(data))
英文:
The middleware reads the request body to EOF. The handler encounters the EOF. The contents of the request body is not cloned in Clone().
To fix the code, restore the request body in the middleware:
data, _ := io.ReadAll(r.Body)
r.Body = io.NopCloser(bytes.NewReader(data))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论