使用Golang读取http.Request.Body中没有内容

注意: 为了简单起见,省略了所有错误处理代码。

在 Golang,我尝试使用下面的代码从 ahttp.Request.Body 中读取来自 POST 请求:

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

它返回了一个空字符串,在 google 搜索之后,我发现了一个关于这个问题的博客: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)
}

有什么建议吗?提前感谢:)

If the request does not include an appropriate "Content-Type" header you may see a 0 length body when you try to read it.

This is happening because you call httputils.DumpRequestOut(req, true) after the http client has performed the request and the body is drained.

Make sure you do the following step in order:

  1. httputils.DumpRequestOut(req, true)
  2. resp, err :=http.DefaultClient.Do(req)
  3. httputil.DumpResponse(res, true)