Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

go - Respond to HTTP request while processing in the background

I have an API that receives a CSV file to process. I'd like to be able to send back an 202 Accepted (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 WaitGroup.Wait() calls, the accepted header isn't sending back. The errors on the handler validation are sending back correctly but that's because of the return statements.

Is it possible to send that 202 Accepted back with the wait groups as I'm hoping (and if so, what am I missing)?

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 < 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.")
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...