Added a mini server sent event handler library

main
Antonio De Lucreziis 4 years ago
parent 8f83a32eab
commit b5aecea322

@ -117,3 +117,7 @@ main {
}
}
}
img {
transform: rotate(180deg);
}

@ -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
}
}
})
}

@ -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)
}
Loading…
Cancel
Save