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,
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.