重复从io.ReadWriter 读取数据.md

如果需要从io.ReadWriter中重复读取数据,比如常见的Response.Body,有多个地方需要读取,可以使用类似如下代码解决这个问题。

// Read the content
var bodyBytes []byte
if c.Request.Body != nil {
  bodyBytes, _ = ioutil.ReadAll(c.Request.Body)
}

// Restore the io.ReadCloser to its original state
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))

// Use the content
bodyString := string(bodyBytes)

参考原文:Golang: Read from an io.ReadWriter without losing its content

你可能感兴趣的:(重复从io.ReadWriter 读取数据.md)