Skip to content

Instantly share code, notes, and snippets.

@ws6
Forked from ifels/golang_pipe_http_response.go
Created June 23, 2020 18:05
Show Gist options
  • Save ws6/1c26a4073319bf9946ecb04e40e93d23 to your computer and use it in GitHub Desktop.
Save ws6/1c26a4073319bf9946ecb04e40e93d23 to your computer and use it in GitHub Desktop.

Revisions

  1. @ifels ifels renamed this gist May 19, 2014. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. @ifels ifels renamed this gist Apr 10, 2014. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. @ifels ifels created this gist Apr 10, 2014.
    47 changes: 47 additions & 0 deletions golang pipe the http response
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    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)
    }