generated from ElnuDev/go-project
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
35 lines
727 B
35 lines
727 B
2 years ago
|
package api
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"net/http"
|
||
|
|
||
|
"git.elnu.com/ElnuDev/shiritori-go/httputils"
|
||
|
. "git.elnu.com/ElnuDev/shiritori-go/shiritori"
|
||
|
)
|
||
|
|
||
|
func GenerateApiEvents(clients *ClientSet) httputils.Handler {
|
||
|
return httputils.GenerateSseHandler(func(w http.ResponseWriter, r *http.Request) {
|
||
|
sendEvent := func(events ...httputils.SseEvent) {
|
||
|
for _, event := range events {
|
||
|
fmt.Fprint(w, event.Encode())
|
||
|
}
|
||
|
w.(http.Flusher).Flush()
|
||
|
}
|
||
|
sendEvent(clients.PlayerCountEvent(1))
|
||
|
ctx := r.Context()
|
||
|
channel := make(Client)
|
||
|
clients.Connect(channel)
|
||
|
outer:
|
||
|
for {
|
||
|
select {
|
||
|
case <-ctx.Done():
|
||
|
clients.Disconnect(channel)
|
||
|
break outer
|
||
|
case events := <-channel:
|
||
|
sendEvent(events...)
|
||
|
}
|
||
|
}
|
||
|
})
|
||
|
}
|