From b5aecea3225f29724c65be6b9109fb1c06fdb051 Mon Sep 17 00:00:00 2001 From: Antonio De Lucreziis Date: Thu, 3 Mar 2022 13:14:46 +0100 Subject: [PATCH] Added a mini server sent event handler library --- client/src/style.scss | 4 +++ server/httputil/serversentevents.go | 38 +++++++++++++++++++++++++++++ server/httputil/sse_test.go | 31 +++++++++++++++++++++++ 3 files changed, 73 insertions(+) create mode 100644 server/httputil/serversentevents.go create mode 100644 server/httputil/sse_test.go diff --git a/client/src/style.scss b/client/src/style.scss index 95c9e4c..06b2a0e 100644 --- a/client/src/style.scss +++ b/client/src/style.scss @@ -117,3 +117,7 @@ main { } } } + +img { + transform: rotate(180deg); +} diff --git a/server/httputil/serversentevents.go b/server/httputil/serversentevents.go new file mode 100644 index 0000000..537a727 --- /dev/null +++ b/server/httputil/serversentevents.go @@ -0,0 +1,38 @@ +package httputil + +import ( + "fmt" + "net/http" +) + +func HandleSSE(handler func(broadcast, single chan<- string)) http.Handler { + broadcast := make(chan string) + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Cache-Control", "no-cache") + w.Header().Set("Connection", "keep-alive") + w.Header().Set("Access-Control-Allow-Origin", "*") + + client := make(chan string) + defer func() { + close(client) + }() + + go handler(broadcast, client) + + flusher, _ := w.(http.Flusher) + for { + select { + case message := <-broadcast: + fmt.Fprintf(w, "%s\n", message) + flusher.Flush() + case message := <-client: + fmt.Fprintf(w, "%s\n", message) + flusher.Flush() + case <-r.Context().Done(): + return + } + } + }) +} diff --git a/server/httputil/sse_test.go b/server/httputil/sse_test.go new file mode 100644 index 0000000..d753b34 --- /dev/null +++ b/server/httputil/sse_test.go @@ -0,0 +1,31 @@ +package httputil_test + +import ( + "net/http" + "testing" + "time" + + "git.phc.dm.unipi.it/aziis98/posti-dm/server/httputil" +) + +func TestSSE(t *testing.T) { + var broadcastChannel chan<- string + + go func() { + for { + if broadcastChannel != nil { + broadcastChannel <- "Messaggio per tutti" + } + time.Sleep(1 * time.Second) + } + }() + + http.Handle("/sse", httputil.HandleSSE(func(broadcast, single chan<- string) { + broadcastChannel = broadcast + time.Sleep(1 * time.Second) + single <- "Messaggio 1 per questo client" + single <- "Messaggio 2 per questo client" + })) + + http.ListenAndServe(":8000", nil) +}