> On 8 Jan 2021, at 1:59 pm, Robert Engels <
ren...@ix.netcom.com> wrote:
>
> You need to pass the context to the expensive work a periodically check if it has been cancelled.
Thanks. I was thinking how to implement this. Is this a nice way to do it?
func clientDisconnected(ctx context.Context, done chan bool) bool {
select {
case <-done:
return false
case <-ctx.Done():
log.Printf("api: client disconnected.")
return true
}
}
func apiHandlerFunction(w http.ResponseWriter, r *http.Request) {
done := make(chan bool)
go func() {
log.Println("First expensive operation")
time.Sleep(5 * time.Second)
done <- true
}()
if clientDisconnected(r.Context(), done) {
return
}
go func() {
log.Println("Second expensive operation")
time.Sleep(5 * time.Second)
done <- true
}()
if clientDisconnected(r.Context(), done) {
return
}
fmt.Fprintf(w, "All operations done")