refactor: support request cancellation in SSE

that's my first use of select on channels, yay
This commit is contained in:
efim 2023-11-05 15:46:07 +00:00
parent bb89b8ccf5
commit 4dbbfcd6f2
1 changed files with 14 additions and 8 deletions

View File

@ -37,14 +37,20 @@ func streamingBsRoute() http.HandlerFunc {
w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Content-Type", "text/event-stream")
startTime, endTime := 0, 0 startTime, endTime := 0, 0
for { for {
log.Printf("another step in streaming bs") select {
data := "data: <div>hello with data %d! waited %d</div> \n\n" case <-r.Context().Done():
startTime = time.Now().Nanosecond() log.Printf("canlecced streaming!")
diff := endTime - startTime return
fmt.Fprintf(w, data, rand.Intn(100), diff) default:
w.(http.Flusher).Flush() log.Printf("another step in streaming bs")
time.Sleep(10 * time.Second) data := "data: <div>hello with data %d! waited %d</div> \n\n"
endTime = time.Now().Nanosecond() startTime = time.Now().Nanosecond()
diff := endTime - startTime
fmt.Fprintf(w, data, rand.Intn(100), diff)
w.(http.Flusher).Flush()
time.Sleep(3 * time.Second)
endTime = time.Now().Nanosecond()
}
} }
} }
} }