解决办法:
//copy first, or Boby will be emptyreqBytes, 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) }
实现代码分析: http://www.cnphp6.com/archives/110001
解决思路来源: