=sse event

This commit is contained in:
Miki 2024-01-06 15:57:12 +00:00
parent c05c44a13e
commit 3b6df8946c
13 changed files with 176 additions and 102 deletions

View file

@ -5,8 +5,10 @@ import (
"log"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
scribble "github.com/nanobox-io/golang-scribble"
)
type Surfer struct {
@ -91,3 +93,78 @@ func (app *App) DeleteHeat(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "deleted"})
}
func (app *App) StartHeatTimer(c *gin.Context) {
var msg Message
var err error
var timer time.Duration
if app.Stream.Start {
c.JSON(http.StatusOK, app.Stream.Duration)
return
}
err = c.ShouldBind(&msg)
if err != nil {
log.Printf("req error: %+v", err)
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
timer, err = time.ParseDuration(msg.Duration)
if err != nil {
log.Printf("req error: %+v", err)
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
app.Stream.Duration = timer
app.Stream.Start = true
startHeat(app.DB, *app.Stream.Heat)
log.Printf("start timer %s - received %s", app.Stream.Duration, msg.Duration)
c.JSON(http.StatusOK, app.Stream.Duration)
}
func (app *App) StopHeatTimer(c *gin.Context) {
if !app.Stream.Start {
c.JSON(http.StatusOK, app.Stream.Duration)
return
}
stopHeat(app.DB, *app.Stream.Heat)
app.Stream.Start = false
app.Stream.Duration = 0
log.Printf("start timer %s", app.Stream.Duration)
c.JSON(http.StatusOK, app.Stream.Duration)
}
func startHeat(db *scribble.Driver, heat Heat) error {
log.Printf("heat: %+v", heat)
heat.Status = "running"
err := db.Write("Heat", heatName(heat), heat)
if err != nil {
log.Printf("set error: %+v", err)
return err
}
return nil
}
func stopHeat(db *scribble.Driver, heat Heat) error {
log.Printf("heat: %+v", heat)
heat.Status = "ended"
err := db.Write("Heat", heatName(heat), heat)
if err != nil {
log.Printf("set error: %+v", err)
return err
}
return nil
}

BIN
sse/be/be

Binary file not shown.

View file

@ -95,7 +95,7 @@ func (e *Event) Stream(c *gin.Context) {
client := &Client{
Ip: c.Request.RemoteAddr,
Chan: make(ClientChan),
Events: c.QueryArray("events"),
Events: c.QueryArray("event"),
}
client.Id = Id(client.Ip, client.Events, 8)

View file

@ -1 +1 @@
{"version":"1704454074172"}
{"version":"1704556541085"}

Binary file not shown.

Binary file not shown.

View file

@ -5,17 +5,17 @@
<link rel="icon" href="/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="modulepreload" href="/_app/immutable/entry/start.WxGgh-q9.js">
<link rel="modulepreload" href="/_app/immutable/entry/start.IlXTmMTk.js">
<link rel="modulepreload" href="/_app/immutable/chunks/scheduler.k-kUyWhY.js">
<link rel="modulepreload" href="/_app/immutable/chunks/singletons.gs6RVdA8.js">
<link rel="modulepreload" href="/_app/immutable/entry/app.Now5kMwx.js">
<link rel="modulepreload" href="/_app/immutable/chunks/singletons.JSxIQYeI.js">
<link rel="modulepreload" href="/_app/immutable/entry/app.sUqO_5CB.js">
<link rel="modulepreload" href="/_app/immutable/chunks/index.PctGSwCt.js">
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">
<script>
{
__sveltekit_1houvg5 = {
__sveltekit_qniv18 = {
base: "",
env: null
};
@ -23,8 +23,8 @@
const element = document.currentScript.parentElement;
Promise.all([
import("/_app/immutable/entry/start.WxGgh-q9.js"),
import("/_app/immutable/entry/app.Now5kMwx.js")
import("/_app/immutable/entry/start.IlXTmMTk.js"),
import("/_app/immutable/entry/app.sUqO_5CB.js")
]).then(([kit, app]) => {
kit.start(app, element);
});

Binary file not shown.

Binary file not shown.

View file

@ -5,17 +5,17 @@
<link rel="icon" href="../favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="modulepreload" href="../_app/immutable/entry/start.WxGgh-q9.js">
<link rel="modulepreload" href="../_app/immutable/entry/start.IlXTmMTk.js">
<link rel="modulepreload" href="../_app/immutable/chunks/scheduler.k-kUyWhY.js">
<link rel="modulepreload" href="../_app/immutable/chunks/singletons.gs6RVdA8.js">
<link rel="modulepreload" href="../_app/immutable/entry/app.Now5kMwx.js">
<link rel="modulepreload" href="../_app/immutable/chunks/singletons.JSxIQYeI.js">
<link rel="modulepreload" href="../_app/immutable/entry/app.sUqO_5CB.js">
<link rel="modulepreload" href="../_app/immutable/chunks/index.PctGSwCt.js">
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">
<script>
{
__sveltekit_1houvg5 = {
__sveltekit_qniv18 = {
base: new URL("..", location).pathname.slice(0, -1),
env: null
};
@ -23,8 +23,8 @@
const element = document.currentScript.parentElement;
Promise.all([
import("../_app/immutable/entry/start.WxGgh-q9.js"),
import("../_app/immutable/entry/app.Now5kMwx.js")
import("../_app/immutable/entry/start.IlXTmMTk.js"),
import("../_app/immutable/entry/app.sUqO_5CB.js")
]).then(([kit, app]) => {
kit.start(app, element);
});

Binary file not shown.

Binary file not shown.

View file

@ -1,93 +1,93 @@
<script>
import { onMount } from'svelte';
import { onMount } from 'svelte';
$: msg = "";
$: jmsg = {};
$: dping = "";
$: dpong = "";
$: msg = '';
$: jmsg = {};
$: dping = '';
$: dpong = '';
function now() {
const now = new Date(Date.now());
function now() {
const now = new Date(Date.now());
return now.toISOString();
}
return now.toISOString();
}
function SSEMsg() {
const sse = new EventSource(`/api/sse?events=ping,pong`);
function SSEMsg() {
const sse = new EventSource(`/api/sse?event=ping&event=pong`);
console.log('subscribe ping pong');
sse.onopen = () => {
console.log(`sse open ${now()}`);
msg = `sse open ${now()}`;
};
sse.onopen = () => {
console.log(`sse open ${now()}`);
msg = `sse open ${now()}`;
};
sse.addEventListener('ping', (e) => {
let Msg = JSON.parse(e.data);
msg = `ping: ${Msg.id} ${Msg.data} ${now()}`;
console.log(msg);
dping = Msg.id;
});
sse.addEventListener('pong', (e) => {
let Msg = JSON.parse(e.data);
msg = `pong: ${Msg.id} ${Msg.data} ${now()}`;
console.log(msg);
dpong = Msg.id;
});
sse.addEventListener('ping', (e) => {
let Msg = JSON.parse(e.data);
msg = `ping: ${Msg.id} ${Msg.data} ${now()}`;
console.log(msg);
dping = Msg.id;
});
return () => {
sse.addEventListener('pong', (e) => {
let Msg = JSON.parse(e.data);
msg = `pong: ${Msg.id} ${Msg.data} ${now()}`;
console.log(msg);
dpong = Msg.id;
});
return () => {
sse.close();
console.log(`sse closing ${Date.now()}`);
};
}
}
function Subscribe() {
function Subscribe() {
const sse = new EventSource(`/api/sse`);
console.log('subscribe');
sse.onopen = () => {
console.log(`sse open ${now()}`);
msg = `sse open ${now()}`;
};
sse.onerror = () => {
console.log(`sse error ${now()}`);
if (sse.readyState === EventSource.CONNECTING) {
console.log(`sse reconnecting ${now()}`);
msg = `sse reconnecting ${now()}`;
} else {
msg = `sse error ${now()}`;
}
};
sse.onopen = () => {
console.log(`sse open ${now()}`);
msg = `sse open ${now()}`;
};
sse.onerror = () => {
console.log(`sse error ${now()}`);
if (sse.readyState === EventSource.CONNECTING) {
console.log(`sse reconnecting ${now()}`);
msg = `sse reconnecting ${now()}`;
} else {
msg = `sse error ${now()}`;
}
};
sse.onmessage = (e) => {
let Msg = JSON.parse(e.data);
console.log(`received: ${JSON.stringify(Msg)}`);
msg = `received: ${JSON.stringify(Msg)} ${now()}`;
jmsg = Msg;
msg = `received: ${JSON.stringify(Msg)} ${now()}`;
jmsg = Msg;
};
sse.addEventListener('ping', (e) => {
let Msg = JSON.parse(e.data);
msg = `ping: ${Msg.id} ${Msg.data} ${now()}`;
console.log(msg);
dping = Msg.id;
});
sse.addEventListener('pong', (e) => {
let Msg = JSON.parse(e.data);
msg = `pong: ${Msg.id} ${Msg.data} ${now()}`;
console.log(msg);
dpong = Msg.id;
});
sse.addEventListener('msg', (e) => {
let Msg = JSON.parse(e.data);
msg = `Msg: ${Msg.id} ${Msg.data} ${now()}`;
console.log(msg);
})
return () => {
sse.addEventListener('ping', (e) => {
let Msg = JSON.parse(e.data);
msg = `ping: ${Msg.id} ${Msg.data} ${now()}`;
console.log(msg);
dping = Msg.id;
});
sse.addEventListener('pong', (e) => {
let Msg = JSON.parse(e.data);
msg = `pong: ${Msg.id} ${Msg.data} ${now()}`;
console.log(msg);
dpong = Msg.id;
});
sse.addEventListener('msg', (e) => {
let Msg = JSON.parse(e.data);
msg = `Msg: ${Msg.id} ${Msg.data} ${now()}`;
console.log(msg);
});
return () => {
sse.close();
console.log(`sse closing ${Date.now()}`);
};
@ -98,40 +98,37 @@
// return unsub;
// });
async function newmsg() {
await fetch('/api/msg');
}
async function Ping() {
await fetch('/api/ping');
}
async function Pong() {
await fetch('/api/pong');
}
async function newmsg() {
await fetch('/api/msg');
}
async function Ping() {
await fetch('/api/ping');
}
async function Pong() {
await fetch('/api/pong');
}
</script>
<h1>{msg}</h1>
<ul>
<li>{jmsg.event}</li>
<li>{jmsg.data}</li>
<li>{jmsg.id}</li>
<li>{jmsg.event}</li>
<li>{jmsg.data}</li>
<li>{jmsg.id}</li>
</ul>
<br>
<br />
<h2>Ping: {dping}</h2>
<br>
<br />
<h2>Pong: {dpong}</h2>
<button on:click={newmsg}>send Msg</button>
<button on:click={Ping}>send Ping</button>
<button on:click={Pong}>send Pong</button>
<hr>
<hr />
<button on:click={SSEMsg}>SSE PingPong</button>
<br>
<br />
<button on:click={Subscribe}>SSE ALL</button>