how to stream data from golang using goroutines

Viewed 26

I want to stream data from server to a web client in chunks.

I have an array of length 20 and I want to send it to the client in chunks of size 2.

However, the response I received on the client is the entire array of size 20. Please help thanks enter image description here


func main() {
    http.HandleFunc("/v2/download", HandleDownloadV2)
    log.Println("Listening for requests at http://localhost:8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func HandleDownloadV2(w http.ResponseWriter, r *http.Request) {
    flusher, ok := w.(http.Flusher)
    if !ok {
        panic("expected http.ResponseWriter to be an http.Flusher")
    }
    
    w.Header().Set("X-Content-Type-Options", "nosniff")
    w.Header().Set("Access-Control-Allow-Origin", "*")
    
    numWorkers := 10
    ch := make(chan string, numWorkers)

    payload := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t"}
    stepSize := len(payload) / numWorkers

    for i := 0; i < numWorkers; i++ {
        go func(n int) {
            msg := strings.Join(payload[n * stepSize: n * stepSize + stepSize], ",") + ","

            // simulate expensive CPU operation
            sum := 0
            for v := 0; v < 10000000000; v++ {
                sum++
            }

            ch <- msg
        }(i)
    }

    for v := 0; v < numWorkers; v++ {
        elem := <- ch
        fmt.Fprintf(w, "%s", elem)
        flusher.Flush()
    }

    close(ch)
}
0 Answers
Related