[Solved] Respond to HTTP request while processing in the background


You’re doing all the processing in the background, but you’re still waiting for it to finish. The solution would be to just not wait. The best solution would move all of the handling elsewhere to a function you can just call with go to run it in the background, but the simplest solution leaving it inline would just be

w.WriteHeader(http.StatusAccepted)
go func() {
    // START PRODUCER/CONSUMER
    jobs := make(chan *Job, 100)    // buffered channel
    results := make(chan *Job, 100) // buffered channel

    // start consumers
    for i := 0; i < 5; i++ { // 5 consumers
        wg.Add(1)
        go consume(i, jobs, results)
    }
    // start producing
    go produce(jobs, csvFile)

    // start processing
    wg2.Add(1)
    go process(results)

    wg.Wait() // wait for all workers to finish processing jobs

    close(results)

    wg2.Wait() // wait for process to finish

    log.Println("===> Done Processing.")
}()

Note that you elided the CSV file handling, so you’ll need to ensure that it’s safe to use this way (i.e. that you haven’t defered closing or deleting the file, which would cause that to occur as soon as the handler returns).

1

solved Respond to HTTP request while processing in the background