doutui9606 2018-03-15 05:01
浏览 118

bytes.Buffer ReadFrom与r.Read不同吗?

I have a situation where I want to take a stream of data from an io Reader and buffer it before sending it as a stream over http post, in the case of connection errors. For this I'm planning to use a bytes.Buffer and copy from the reader to the buffer. A separate goroutine would read from the buffer and pass the reader to a http.Request.

Now, the behavior from bytes.Buffer ReadFrom is not what I'm expecting. I'm simulating a data stream with a pipe:

r, w := io.Pipe()
go func() {
    for i := 0; i < 10; i++ {
        w.Write([]byte(fmt.Sprintf("foobar %d
", i)))
        time.Sleep(200 * time.Millisecond)
    }
    w.Close()
}()

When reading from the reader into a byte slice, the Read returns after each write, however, when using ReadFrom, it doesn't stop reading until the writer is closed. This:

    buf := &bytes.Buffer{}
    nIn, err = buf.ReadFrom(r)

reads all ten lines before returning, while:

    buf := make([]byte, 64)
    nIn, err = r.Read(buf)

returns after each line. Why is the behavior different?

  • 写回答

1条回答 默认 最新

  • doushifen4060 2018-03-15 05:15
    关注

    The behavior of io.Reader (Read) is defined to be different from io.ReadFrom.

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100