在`ResponseWriter`上进行实时应用程序的大量写入操作

huangapple go评论82阅读模式
英文:

Go realtime application heavy writes on ResponseWriter

问题

我有一个需要不断向http.ResponseWriter写入内容(可能永远不停止)并将这些输出显示到HTML页面的Web应用程序。大致如下所示:

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

我感觉HTML输出的速度跟不上。如果我想要尽可能实时地在HTML上保持向http.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

得分: 3

默认的http.ResponseWriter使用bufio.ReadWriter作为底层连接,它会对所有写入进行缓冲。如果你希望数据尽快发送,你需要在每次写入后刷新缓冲区。

net/http包中有一个http.Flusher接口,它由默认的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()
            }
        }
    }
}

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

英文:

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.

huangapple
  • 本文由 发表于 2015年12月24日 15:51:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/34449225.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定