You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
39 lines
816 B
Go
39 lines
816 B
Go
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
|
|
}
|
|
}
|
|
})
|
|
}
|