Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vedhavyas/f7bf0a8259b289097e026039756bfc3f to your computer and use it in GitHub Desktop.
Save vedhavyas/f7bf0a8259b289097e026039756bfc3f to your computer and use it in GitHub Desktop.
golang pipe the http response
package main
import (
"io"
"net/http"
"os/exec"
)
var (
BUF_LEN = 1024
)
func handler(w http.ResponseWriter, r *http.Request) {
cmd := exec.Command("./build.sh")
pipeReader, pipeWriter := io.Pipe()
cmd.Stdout = pipeWriter
cmd.Stderr = pipeWriter
go writeCmdOutput(w, pipeReader)
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
}
}
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment