Compare commits
1 Commits
db2d7d0252
...
90a3d9e5a5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90a3d9e5a5 |
@@ -1,7 +1,6 @@
|
||||
package c4game
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -18,6 +17,7 @@ import (
|
||||
"github.com/ryanhamamura/games/db/repository"
|
||||
"github.com/ryanhamamura/games/features/c4game/pages"
|
||||
"github.com/ryanhamamura/games/sessions"
|
||||
appsse "github.com/ryanhamamura/games/sse"
|
||||
)
|
||||
|
||||
// c4ChatColors maps player color (1=Red, 2=Yellow) to CSS background colors.
|
||||
@@ -120,8 +120,7 @@ func HandleGameEvents(store *connect4.Store, nc *nats.Conn, sm *scs.SessionManag
|
||||
}
|
||||
|
||||
sendPing := func() error {
|
||||
ping, _ := json.Marshal(map[string]int64{"lastPing": time.Now().UnixMilli()})
|
||||
return sse.PatchSignals(ping)
|
||||
return appsse.SendPing(sse)
|
||||
}
|
||||
|
||||
// Send initial render and ping
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package snakegame
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -17,6 +16,7 @@ import (
|
||||
"github.com/ryanhamamura/games/features/snakegame/pages"
|
||||
"github.com/ryanhamamura/games/sessions"
|
||||
"github.com/ryanhamamura/games/snake"
|
||||
appsse "github.com/ryanhamamura/games/sse"
|
||||
)
|
||||
|
||||
func snakeChatColor(slot int) string {
|
||||
@@ -126,8 +126,7 @@ func HandleSnakeEvents(snakeStore *snake.SnakeStore, nc *nats.Conn, sm *scs.Sess
|
||||
}
|
||||
|
||||
sendPing := func() error {
|
||||
ping, _ := json.Marshal(map[string]int64{"lastPing": time.Now().UnixMilli()})
|
||||
return sse.PatchSignals(ping)
|
||||
return appsse.SendPing(sse)
|
||||
}
|
||||
|
||||
// Send initial render and ping
|
||||
|
||||
28
sse/signals.go
Normal file
28
sse/signals.go
Normal file
@@ -0,0 +1,28 @@
|
||||
// Package sse provides helpers for SSE signal handling.
|
||||
package sse
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/starfederation/datastar-go/datastar"
|
||||
)
|
||||
|
||||
// Signals holds client-side state managed via SSE.
|
||||
type Signals struct {
|
||||
LastPing int64 `json:"lastPing,omitempty"`
|
||||
}
|
||||
|
||||
// SendPing sends a heartbeat signal with the current timestamp.
|
||||
func SendPing(sse *datastar.ServerSentEventGenerator) error {
|
||||
return PatchSignals(sse, Signals{LastPing: time.Now().UnixMilli()})
|
||||
}
|
||||
|
||||
// PatchSignals sends a signals patch to the client.
|
||||
func PatchSignals(sse *datastar.ServerSentEventGenerator, s Signals) error {
|
||||
data, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return sse.PatchSignals(data)
|
||||
}
|
||||
Reference in New Issue
Block a user