douxiangbiao1899 2016-08-31 22:49
浏览 295

从正在Go中使用块传输的http服务器读取和流式传输响应

I have an http server that responds to requests via the chunk protocol. In this simple example, it responds with the time every second. I have another server that forwards requests to this time server and respond with the same chunk protocol.

curl -i localhost:8000 returns the right thing

however curl -i localhost:9000 returns a chunked response but only after three seconds (not every second). This means that somehow io.copy does not really flush the output as soon as it comes

  • 写回答

1条回答 默认 最新

  • dtn55928 2016-09-01 00:39
    关注

    io.Copy has to copy the entire contents before you call Flush. If you want the contents sent before the buffer has filled, you need to call flush after each write yourself.

    A complete version of io.Copy that flushes an http.ResponseWriter after each write would look like:

    func flushCopy(dst io.Writer, src io.Reader) (written int64, err error) {
        buf := make([]byte, 1024 * 8)
        flusher, canFlush := dst.(http.Flusher)
        for {
            nr, er := src.Read(buf)
            if nr > 0 {
                nw, ew := dst.Write(buf[0:nr])
                if nw > 0 {
                    if canFlush {
                        flusher.Flush()
                    }
                    written += int64(nw)
                }
                if ew != nil {
                    err = ew
                    break
                }
                if nr != nw {
                    err = io.ErrShortWrite
                    break
                }
            }
            if er == io.EOF {
                break
            }
            if er != nil {
                err = er
                break
            }
        }
        return written, err
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么