jk
All checks were successful
Docker Deploy / build-and-push (push) Successful in 1m9s

This commit is contained in:
Atridad Lahiji 2025-03-24 01:30:59 -06:00
parent 497abfe83f
commit 2560ff159c
Signed by: atridad
SSH key fingerprint: SHA256:LGomp8Opq0jz+7kbwNcdfTcuaLRb5Nh0k5AchDDb438
2 changed files with 10 additions and 42 deletions

View file

@ -27,45 +27,36 @@ func SSE(c echo.Context) error {
// Use the request context, which is cancelled when the client disconnects
ctx := c.Request().Context()
// Set headers for SSE
// Standard SSE headers
c.Response().Header().Set("Content-Type", "text/event-stream")
c.Response().Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
c.Response().Header().Set("Cache-Control", "no-cache")
c.Response().Header().Set("Connection", "keep-alive")
c.Response().Header().Set("Pragma", "no-cache")
c.Response().Header().Set("Expires", "0")
c.Response().Header().Set("X-Accel-Buffering", "no")
// Set CORS headers
// CORS headers
origin := c.Request().Header.Get("Origin")
if origin == "https://atri.dad" || origin == "http://localhost:3000" {
c.Response().Header().Set("Access-Control-Allow-Origin", origin)
c.Response().Header().Set("Access-Control-Allow-Credentials", "true")
} else {
// Allow any origin as fallback for testing
c.Response().Header().Set("Access-Control-Allow-Origin", "*")
}
// Set response status
// Prepare the response
c.Response().WriteHeader(http.StatusOK)
c.Response().Flush()
// Create a channel to receive messages
// Client channel for SSE messages
clientChan := make(chan string)
// Add the client to the SSEServer
lib.SSEServer.AddClient(channel, clientChan)
// Clean up when the connection is closed
defer lib.SSEServer.RemoveClient(channel, clientChan)
// Write the initial message
initialMsg := ": connected\n\n"
if _, err := c.Response().Write([]byte(initialMsg)); err != nil {
// Write initial message
if _, err := c.Response().Write([]byte("data: Connected to SSE server\n\n")); err != nil {
return err
}
c.Response().Flush()
// Create a ticker for keep-alive messages
// Keep-alive ticker
ticker := time.NewTicker(15 * time.Second)
defer ticker.Stop()
@ -73,7 +64,6 @@ func SSE(c echo.Context) error {
for {
select {
case <-ctx.Done():
// Client disconnected
return nil
case <-ticker.C:
// Send keep-alive comment
@ -82,7 +72,7 @@ func SSE(c echo.Context) error {
}
c.Response().Flush()
case msg := <-clientChan:
// Format the SSE message
// Format as standard SSE message
data := fmt.Sprintf("data: %s\n\n", msg)
if _, err := c.Response().Write([]byte(data)); err != nil {
return err

View file

@ -19,7 +19,7 @@ A demo of my SSE implementation.
<p class="text-lg">This page demonstrates the use of the <a href="https://htmx.org/extensions/sse/">HTMX SSE
Extension</a> to receive Server Sent Events on the "default" channel.</p>
<p class="text-lg">Any events received on the "default" channel will appear below:</p>
<div id="sse-target" hx-ext="sse" sse-connect="/api/sse" sse-swap="message">
<div hx-ext="sse" sse-connect="/api/sse" sse-swap="message">
Waiting for SSE Message...
</div>
@ -37,26 +37,4 @@ A demo of my SSE implementation.
{{define "foot"}}
<script src="/public/js/htmx.sse.js"></script>
<script>
// Custom EventSource factory with better retry handling
htmx.createEventSource = function(url) {
console.log("Creating EventSource for:", url);
// Create EventSource with credentials
const source = new EventSource(url, { withCredentials: true });
// Log connection state changes
source.onopen = function() {
console.log("SSE connection opened successfully");
document.getElementById('sse-target').innerHTML = "Connected to SSE. Waiting for messages...";
};
source.onerror = function(err) {
console.error("SSE connection error:", err);
document.getElementById('sse-target').innerHTML = "Connection error. Retrying...";
};
return source;
};
</script>
{{end}}