“尝试读取请求体后,无法解码 JSON 数据:EOF”

huangapple go评论89阅读模式
英文:

'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))

huangapple
  • 本文由 发表于 2023年2月11日 00:48:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75413944.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定