ioutils.ReadAll()会清空对应的reader

本文介绍在Golang中如何正确处理HTTP请求体的读取及重置问题,避免因重复读取而导致的数据丢失。通过示例展示了如何使用bytes.Buffer实现数据的“预览”功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载于: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)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值