Note that there are some explanatory texts on larger screens.

plurals
  1. PONot buffered http.ResponseWritter in Golang
    text
    copied!<p>I'm writing a simple web app in Go and I want my responses to be streamed to the client (i.e. not buffered and sent in blocks once the request is fully processed) :</p> <pre><code>func handle(res http.ResponseWriter, req *http.Request) { fmt.Fprintf(res, "sending first line of data") sleep(10) //not real code fmt.Fprintf(res, "sending second line of data") } </code></pre> <p>From the client point of view, the two lines will be sent at the same time. Any suggestions are appreciated :)</p> <h3>Edit after @dystroy answer</h3> <p>It's possible to flush after each write I personally make, but in my use case it's not enough:</p> <pre><code>cmd := exec.Command("a long command that outputs lots of lines") cmd.Stdout = res //where res is a http.ResponseWritter cmd.Stderr = res err := cmd.Run() </code></pre> <p>I want the output of my <code>cmd</code> to be flushed as well. Anyway to "autoflush" the ResponseWritter ?</p> <h3>Solution</h3> <p>I found help on golang's mailing list. There is 2 way to achieve this: using <a href="http://golang.org/pkg/net/http/#example_Hijacker" rel="noreferrer">hijacker</a> that allow to take over the underlying TCP connection of HTTP, or piping the stdout and stderr of the command in a go routine that will write and flush :</p> <pre><code>pipeReader, pipeWriter := io.Pipe() cmd.Stdout = pipeWriter cmd.Stderr = pipeWriter go writeCmdOutput(res, pipeReader) err := cmd.Run() pipeWriter.Close() //--------------------- func writeCmdOutput(res http.ResponseWriter, pipeReader *io.PipeReader) { buffer := make([]byte, BUF_LEN) for { n, err := pipeReader.Read(buffer) if err != nil { pipeReader.Close() break } data := buffer[0:n] res.Write(data) if f, ok := res.(http.Flusher); ok { f.Flush() } //reset buffer for i := 0; i &lt; n; i++ { buffer[i] = 0 } } } </code></pre> <h3>Last update</h3> <p>Even nicer: <a href="http://play.golang.org/p/PpbPyXbtEs" rel="noreferrer">http://play.golang.org/p/PpbPyXbtEs</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload