注意:为简单起见,省略了所有错误处理代码。我在本地处理它们,没有产生任何错误。
在Golang中,我尝试使用以下代码从POST请求中读取http.Request.Body
:
func readBody(req *http.Request) string {
bytes, _ := httputils.DumpRequestOut(req, true)
return string(bytes)
}
它显示非零内容长度,但没有返回内容:
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)
}
有什么建议吗?在此先感谢:)
答案 0 :(得分:0)
如果请求中没有包含适当的" Content-Type"当您尝试阅读它时,您可能会看到一个0长度的正文。
答案 1 :(得分:0)
之所以发生这种情况,是因为您在http客户端执行了请求并且正文耗尽后调用了httputils.DumpRequestOut(req, true)
。
确保按顺序执行以下步骤:
httputils.DumpRequestOut(req, true)
resp, err :=http.DefaultClient.Do(req)
httputil.DumpResponse(res, true)