douningzhi1991 2015-12-24 07:51
浏览 31
已采纳

实时应用大量写在ResponseWriter上

I have a web application that needs to keep writing (possibly never ending) tohttp.ResponseWriter, and to display those output to html page. It's something like:

func handler(w http.ResponseWriter, req *http.Request) {
     switch req.Method {
         case "GET":
              for {
                  fmt.Fprintln(w, "repeating...")
              }
     }
}

I feel like the HTML output does not catch up fast enough.

If I want to keep writing on http.ResponseWriter and display those on HTML as fast as possible in realtime, what would be the best way to achieve this?

Thanks,

  • 写回答

1条回答 默认 最新

  • dongshi1188 2015-12-24 10:52
    关注

    The default http.ResponseWriter uses a bufio.ReadWriter for the underlying connection, which buffers all writes. You have to flush the buffer after every write, if you want your data to be sent as fast as possible.

    There is a http.Flusher interface for this in the net/http package, that is implemented by the default http.ResponseWriter.

    With this you could rewrite your example as follows:

    func handler(w http.ResponseWriter, req *http.Request) {
         switch req.Method {
         case "GET":
              for {
                  fmt.Fprintln(w, "repeating...")
    
                  if f, ok := w.(http.Flusher); ok {
                      f.Flush()
                  }
              }
         }
    }
    

    This will flush the internal buffer after every write.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 Ubuntu20.04无法连接GitHub
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥30 C++行情软件的tick数据如何高效的合成K线