美文网首页
重复从io.ReadWriter 读取数据.md

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

作者: kker | 来源:发表于2016-11-10 10:32 被阅读225次

如果需要从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

      本文链接:https://www.haomeiwen.com/subject/bdztpttx.html