Skip to content

Commit

Permalink
implement Server-sent events support (#365)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ethosa committed Jan 17, 2025
1 parent 8fb8ec7 commit 80d0e2f
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 0 deletions.
87 changes: 87 additions & 0 deletions tests/index_sse.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<!DOCTYPE html>
<html>
<head>
<title>SSE Demo with HTMX</title>
<script src="https://unpkg.com/[email protected]"></script>
<script src="https://unpkg.com/[email protected]/sse.js"></script>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 20px auto;
padding: 0 20px;
}
#messages {
height: 400px;
width: 100%;
overflow-y: auto;
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
background: #f9f9f9;
}
.message {
margin: 5px 0;
padding: 8px;
border-bottom: 1px solid #eee;
background: white;
border-radius: 4px;
animation: fadeIn 0.5s;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(-10px); }
to { opacity: 1; transform: translateY(0); }
}
.timestamp {
color: #666;
font-size: 0.8em;
}
#status {
padding: 10px;
margin: 10px 0;
border-radius: 4px;
}
.connected {
background-color: #dff0d8;
color: #3c763d;
}
.disconnected {
background-color: #f2dede;
color: #a94442;
}
.time-event { color: #31708f; }
.open-event { color: #3c763d; }
.heartbeat-event { color: #777; }
.price-event { color: #8f0a1a; }
</style>
</head>
<body>
<h1>Server-Sent Events Demo (HTMX)</h1>

<!-- Current Time -->
<div id="current-time"
class="message time-event"
hx-ext="sse"
sse-connect="http://127.0.0.1:5000/sse"
sse-swap="time">
Waiting for time update...
</div>

<script>
let source = new EventSource("http://127.0.0.1:5000/sse");

source.addEventListener('join', event => {
console.log(`${event.data}`);
});

source.addEventListener('message', event => {
console.log(`${event.data}`);
});

source.addEventListener('leave', event => {
console.log(`${event.data}`);
});
</script>

</body>
</html>
16 changes: 16 additions & 0 deletions tests/testc21.nim
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,28 @@ import
../src/happyx


regCORS:
methods: "*"
origins: "*"
headers: "*"
credentials: true


serve "127.0.0.1", 5000:
get "/":
""
get "/user/$id":
id
post "/user":
""

# Server-sent events
# https://github.com/HapticX/happyx/discussions/365
sse "/sse":
while true:
let now = now().utc.format("ddd, d MMM yyyy HH:mm:ss")
await req.sseSend("time", now)
await sleepAsync(2500)

notfound:
"method not allowed"

0 comments on commit 80d0e2f

Please sign in to comment.