package main
import (
"context"
"net/http"
"time"
)
var reqChan chan context.Context
func ConcPrinter(reqChan chan context.Context) {
for c := range reqChan {
w := c.Value("reqW").(http.ResponseWriter)
f := c.Value("cancel").(context.CancelFunc)
// Expensive operation
time.Sleep(time.Second)
w.Write([]byte("Done!"))
f()
}
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
cont, f := context.WithCancel(context.WithValue(r.Context(), "reqW", w))
contC := context.WithValue(cont, "cancel", f)
reqChan <- contC
<-contC.Done()
}
func main() {
http.HandleFunc("/", rootHandler)
reqChan = make(chan context.Context)
go ConcPrinter(reqChan)
http.ListenAndServe(":8080", nil)
}