title: Respond to HTTP request while processing in the background
body: <p>I have an API that receives a CSV file to process. I'd like to be able to send back an <code>202 Accepted</code> (or any status really) while processing the file in the background. I have a handler that checks the request, writes the success header, and then continues processing via a producer/consumer pattern. The problem is that, due to the <code>WaitGroup.Wait()</code> calls, the accepted header isn't sending back. The errors on the handler validation are sending back correctly but that's because of the <code>return</code> statements.</p>
  <p>Is it possible to send that <code>202 Accepted</code> back with the wait groups as I'm hoping (and if so, what am I missing)?</p>
  <pre class="lang-golang prettyprint-override"><code>func SomeHandler(w http.ResponseWriter, req *http.Request) {
      endAccepted := time.Now()
      err := verifyRequest(req)
      if err != nil {
          w.WriteHeader(http.StatusBadRequest)
          data := JSONErrors{Errors: []string{err.Error()}}
          json.NewEncoder(w).Encode(data)
          return
      }
  
      // ...FILE RETRIEVAL CLIPPED (not relevant)...
      // e.g. csvFile, openErr := os.Open(tmpFile.Name())
  
      //////////////////////////////////////////////////////
      // TODO this isn't sending due to the WaitGroup.Wait()s below
      w.WriteHeader(http.StatusAccepted)
      //////////////////////////////////////////////////////
  
      // START PRODUCER/CONSUMER
      jobs := make(chan *Job, 100)    // buffered channel
      results := make(chan *Job, 100) // buffered channel
  
      // start consumers
      for i := 0; i &lt; 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(&quot;===&gt; Done Processing.&quot;)
  }
  </code></pre>