Implemented server sent events

This commit is contained in:
2018-11-07 05:40:03 +09:00
parent 61454b3e5b
commit e56782d5a3
6 changed files with 81 additions and 1 deletions

View File

@ -4,6 +4,7 @@ import (
"strings"
"github.com/animenotifier/notify.moe/pages/post"
"github.com/animenotifier/notify.moe/pages/sse"
"github.com/animenotifier/notify.moe/pages/thread"
"github.com/aerogo/aero"
@ -42,6 +43,9 @@ func Register(l *layout.Layout, app *aero.Application) {
app.Get("/api/next/soundtrack", soundtrack.Next)
app.Get("/api/character/:id/ranking", character.Ranking)
// Live updates
app.Get("/api/sse/events", sse.Events)
// Thread
app.Get("/api/thread/:id/reply/ui", thread.ReplyUI)

42
pages/sse/sse.go Normal file
View File

@ -0,0 +1,42 @@
package sse
import (
"fmt"
"net/http"
"github.com/aerogo/aero"
"github.com/animenotifier/notify.moe/utils"
)
// Events streams server events to the client.
func Events(ctx *aero.Context) string {
user := utils.GetUser(ctx)
if user == nil {
return ctx.Error(http.StatusUnauthorized, "Not logged in")
}
fmt.Println(user.Nick, "receiving live events")
events := make(chan *aero.Event)
disconnected := make(chan struct{})
go func() {
defer fmt.Println(user.Nick, "disconnected, stop sending events")
for {
select {
case <-disconnected:
close(events)
return
// case <-time.After(10 * time.Second):
// events <- &aero.Event{
// Name: "ping",
// }
}
}
}()
return ctx.EventStream(events, disconnected)
}