Go 实时应用程序大量写入 ResponseWriter

Go realtime application heavy writes on ResponseWriter

我有一个 Web 应用程序需要不断写入(可能永远不会结束)http.ResponseWriter,并将这些输出显示到 html 页面。它是这样的:

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

我觉得 HTML 输出跟不上速度。

如果我想在 http.ResponseWriter 上继续书写并尽可能快地实时显示在 HTML 上,最好的方法是什么?

谢谢,

底层连接的默认值 http.ResponseWriter uses a bufio.ReadWriter,它缓冲所有写入。如果您希望尽快发送数据,则必须在每次写入后刷新缓冲区。

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

有了这个你可以重写你的例子如下:

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()
              }
          }
     }
}

这将在每次写入后刷新内部缓冲区。