TIL
http.Response.Body是一个缓冲区,这意味着一旦读取它,就不能再次读取它。
就像水流一样,您可以看到它并在流过时对其进行测量,但是一旦流失,它就消失了。
但是,知道这一点,有一种解决方法,您需要“捕获”主体并将其还原:
// Read the Body contentvar bodyBytes []byteif context.Request().Body != nil { bodyBytes, _ = ioutil.ReadAll(context.Request().Body)}// Restore the io.ReadCloser to its original statecontext.Request().Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))// Continue to use the Body, like Binding it to a struct:order := new(models.GeaOrder)error := context.Bind(order)现在,您可以在
context.Request().Body其他地方使用。
资料来源:
http://grokbase.com/t/gg/golang-nuts/12adq8a2ys/go-nuts-re-reading-http-
response-body-or-any-reader
https://medium.com/@xoen/golang-read-from-an-io-readwriter-without-loosing-
its-content-2c6911805361



