【发布时间】:2015-12-22 21:27:37
【问题描述】:
注意:为简单起见,省略了所有错误处理代码。我在本地处理,没有产生错误。
在 Golang 中,我尝试使用以下代码从 POST 请求中读取 http.Request.Body:
func readBody(req *http.Request) string {
bytes, _ := httputils.DumpRequestOut(req, true)
return string(bytes)
}
它显示一个非零的 Content-Length,但没有返回内容:
ContentLength=413 with Body length 0
。我尝试了下面的代码,也没有运气:
func readBody(req *http.Request) string {
bytes, _ := ioutil.ReadAll(req.Body)
return string(bytes)
}
它返回一个空字符串。谷歌搜索后,我发现了一个关于这个问题的博客:Golang: Read from an io.ReadWriter without losing its content。我试图遵循模式,仍然没有运气:
func readBody(req *http.Request) string {
bodyBytes, _ := ioutil.ReadAll(req.Body)
// Restore the io.ReadCloser to its original state
req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
// Use the content
return string(bodyBytes)
}
有什么建议吗?在此先感谢:)
【问题讨论】:
-
检查返回的错误(那些你优雅省略的代码中的下划线
'_')。如果您无法基于此弄清楚它们是什么,请发布它们。还要发布您如何获取传递给上述函数的http.Request(例如发布调用readBody()函数的上下文)。 -
哦,我忘了说我把 _ 用于所有错误只是为了简单起见。我在代码中正确处理了它们,没有发现错误。
-
你确定真的有是一个非空的身体吗?如果是:你为什么确定?
-
我已经添加了我在问题中得到的内容,类似于
ContentLength=413 with Body length 0。这是我应该进入身体的假定内容吗?是不是因为它是一个 POST 请求,所以 Body 不应该包含任何内容? -
所以没有正文。内容长度可能是错误的。很多请求没有正文。