From 4dbbfcd6f20ba477a3cc6eaa5a5a5705563b633b Mon Sep 17 00:00:00 2001 From: efim Date: Sun, 5 Nov 2023 15:46:07 +0000 Subject: [PATCH] refactor: support request cancellation in SSE that's my first use of select on channels, yay --- routes/room_page.go | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/routes/room_page.go b/routes/room_page.go index 513029f..b5f3cb8 100644 --- a/routes/room_page.go +++ b/routes/room_page.go @@ -37,14 +37,20 @@ func streamingBsRoute() http.HandlerFunc { w.Header().Set("Content-Type", "text/event-stream") startTime, endTime := 0, 0 for { - log.Printf("another step in streaming bs") - data := "data:
hello with data %d! waited %d
\n\n" - startTime = time.Now().Nanosecond() - diff := endTime - startTime - fmt.Fprintf(w, data, rand.Intn(100), diff) - w.(http.Flusher).Flush() - time.Sleep(10 * time.Second) - endTime = time.Now().Nanosecond() + select { + case <-r.Context().Done(): + log.Printf("canlecced streaming!") + return + default: + log.Printf("another step in streaming bs") + data := "data:
hello with data %d! waited %d
\n\n" + 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() + } } } }