Home >Backend Development >Golang >How Can I Send Real-Time Data with Unbuffered HTTP Responses in Go?

How Can I Send Real-Time Data with Unbuffered HTTP Responses in Go?

Susan Sarandon
Susan SarandonOriginal
2024-12-17 21:06:15214browse

How Can I Send Real-Time Data with Unbuffered HTTP Responses in Go?

Sending Real-Time Data with Unbuffered HTTP Responses in Go

In Go, HTTP responses are commonly buffered before being sent to the client. However, for streaming or real-time applications, it's crucial to send data incrementally without buffering.

To achieve unbuffered responses, you can leverage the Flusher interface implemented by some ResponseWriter. By flushing the response after each write operation, you can send data directly to the client as it becomes available. Here's an example:

func handle(res http.ResponseWriter, req *http.Request) {
  fmt.Fprintf(res, "sending first line of data")
  if f, ok := res.(http.Flusher); ok {
    f.Flush()
  }
  sleep(10) // Not real code
  fmt.Fprintf(res, "sending second line of data")
}

While this approach works for manual writes, it may not suffice for piping command output or other scenarios where data comes asynchronously. In such cases, you can utilize a Go routine to read and flush the data continuously.

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 < n; i++ {
      buffer[i] = 0
    }
  }
}

This approach ensures that command output is written and flushed directly to the client without buffering. For further convenience, consider using a library like [fasthttp](https://github.com/valyala/fasthttp) that provides built-in support for real-time streaming.

The above is the detailed content of How Can I Send Real-Time Data with Unbuffered HTTP Responses in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn