英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论