+sse (test)

This commit is contained in:
mikif70 2025-03-03 11:33:10 +01:00
parent b6eccadb2e
commit dd020ad794
5 changed files with 75 additions and 91 deletions

View file

@ -26,7 +26,7 @@ func main() {
api := Engine.Group("/api") api := Engine.Group("/api")
api.GET("/sse", SSEHandler) api.GET("/sse", SSEHandler)
api.GET("/status", GetStatus) // api.GET("/status", GetStatus)
api.POST("/status", SetStatus) api.POST("/status", SetStatus)
port := os.Getenv("PORT") port := os.Getenv("PORT")

28
backend/sse.go Normal file
View file

@ -0,0 +1,28 @@
package main
import (
"github.com/gin-gonic/gin"
)
type Message struct {
Data interface{}
}
type Client struct {
Channel chan Message `json:"clients"`
}
func SSEHandler(c *gin.Context) {
}
func registerClient(client *Client) {
}
func unregisterClient(client *Client) {
}
func SendMsg(c *gin.Context) {
}
func handleMessages() {
}

View file

@ -1,87 +0,0 @@
package main
import (
"fmt"
"log"
"net/http"
"sync"
"time"
"github.com/gin-gonic/gin"
)
type Message struct {
Data interface{} `json:"data"`
Id string `json:"id"`
}
type Client struct {
Channel chan Message `json:"clients"`
}
var (
clients = make(map[*Client]bool)
clientsMutex sync.Mutex
broadcast = make(chan Message)
)
func SSEHandler(c *gin.Context) {
client := &Client{
Channel: make(chan Message),
}
log.Printf("events: %+v", client)
AddClient(client)
defer unregisterClient(client)
log.Printf("Client %s connected", client)
c.Writer.Header().Set("Content-Type", "text/event-stream")
c.Writer.Header().Set("Cache-Control", "no-cache")
c.Writer.Header().Set("Connection", "keep-alive")
c.Writer.Header().Set("Transfer-Encoding", "chunked")
for {
select {
case msg := <-client.Channel:
fmt.Fprintf(c.Writer, "data: %s\n\n", msg.Data)
c.Writer.Flush()
case <-c.Writer.CloseNotify():
return
}
}
}
func AddClient(client *Client) {
clientsMutex.Lock()
clients[client] = true
clientsMutex.Unlock()
}
func unregisterClient(client *Client) {
clientsMutex.Lock()
delete(clients, client)
close(client.Channel)
clientsMutex.Unlock()
}
func SendMsg(c *gin.Context) {
var msg Message
c.ShouldBind(&msg)
msg.Id = time.Now().Format(time.RFC3339)
broadcast <- msg
c.JSON(http.StatusOK, gin.H{"status": "sent"})
}
func handleMessages() {
for {
msg := <-broadcast
clientsMutex.Lock()
for client := range clients {
client.Channel <- msg
}
clientsMutex.Unlock()
}
}

View file

@ -12,6 +12,8 @@ import (
type Status struct { type Status struct {
Surfers []Surfer `json:"surfers"` Surfers []Surfer `json:"surfers"`
Round Info `json:"round"` Round Info `json:"round"`
Mins int `json:"mins"`
Secs int `json:"secs"`
Count int `json:"surfersCount"` Count int `json:"surfersCount"`
} }
@ -41,7 +43,15 @@ func initStatus() interface{} {
Color: "lightgray", Color: "lightgray",
Priority: "", Priority: "",
Score: 0, Score: 0,
Delete: false,
}, },
{
Name: "",
Color: "lightgray",
Priority: "",
Score: 0,
Delete: false,
}
}, },
Round: Info{ Round: Info{
Round: "", Round: "",
@ -49,7 +59,9 @@ func initStatus() interface{} {
Category: "", Category: "",
Time: 0, Time: 0,
}, },
Count: 1, Mins: 0,
Secs: 0,
Count: 2,
} }
} }

View file

@ -26,8 +26,39 @@
onMount(async () => { onMount(async () => {
LoadFromLocalCache(); LoadFromLocalCache();
console.log(`onMount: ${JSON.stringify(surfers)}`); console.log(`onMount: ${JSON.stringify(surfers)}`);
// const sse = StartSSE();
// return sse;
}); });
function StartSSE() {
let url = base + "/api/sse?";
for (let e in events) {
url += `event=${events[e]}&`;
}
console.log(`sse url: ${url}`);
const sse = new EventSource(url);
console.log(`subscribe: ${sse}`);
sse.onopen = () => {
console.log(`sse open ${Date.now()}`);
};
sse.addEventListener("status", (e) => {
let Msg = JSON.parse(e.data);
console.log(JSON.stringify(Msg));
console.log(`status: ${Msg.data.round}`);
surfers = Msg.data.surfers;
info = Msg.data.round;
mins = Msg.data.mins;
secs = Msg.data.secs;
});
return () => {
sse.close();
console.log(`sse closing ${Date.now()}`);
};
}
function LoadFromLocalCache() { function LoadFromLocalCache() {
let srf = window.sessionStorage.getItem("surfers"); let srf = window.sessionStorage.getItem("surfers");
if (srf) { if (srf) {
@ -436,11 +467,11 @@
width: 100%; width: 100%;
align-content: center; align-content: center;
} }
.surfer ul { /* .surfer ul {
list-style-type: none; list-style-type: none;
margin-left: 0px; margin-left: 0px;
padding-left: 0px; padding-left: 0px;
} } */
.surfer select { .surfer select {
-moz-appearance: none; /* Firefox */ -moz-appearance: none; /* Firefox */
-webkit-appearance: none; /* Safari and Chrome */ -webkit-appearance: none; /* Safari and Chrome */