转载于:http://blog.youkuaiyun.com/pkueecser/article/details/50421562
解决方法
reqBytes, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
log.Error("fail to read requset data")
return 0, err
}
log.Infof("%s", reqBytes)
buf := bytes.NewBuffer(reqBytes)
c.Request.Body = ioutil.NopCloser(buf)
分析原因
http://stackoverflow.com/questions/30910487/why-an-io-reader-after-read-it-became-empty-in-golang
Reading from a bytes.Buffer drains or consumes the bytes that were read. This means if you try to read again those will not be returned.
Buffer.Bytes() returns the unread portion of the buffer so it is the expected result for you to see 0 length after everything has been read (this is exactly what ioutil.ReadAll() does).
What if you just want to "peek" and not really "read" bytes?
There is no "peek" functionality in bytes.Buffer. The easiest would be to get the bytes of the buffer, and construct another bytes.Buffer from it and read from the new buffer.
It could look something like this:
func peek(buf *bytes.Buffer, b []byte) (int, error) {
buf2 := bytes.NewBuffer(buf.Bytes())
return buf2.Read(b)
}