pollo/api/sse.go

61 lines
1.5 KiB
Go
Raw Permalink Normal View History

2023-05-18 20:04:55 -06:00
package api
import (
"fmt"
2024-06-04 15:40:29 -06:00
"time"
2023-05-18 20:04:55 -06:00
"github.com/labstack/echo/v4"
2024-06-27 13:13:46 -06:00
"pollo/lib"
2023-05-18 20:04:55 -06:00
)
2024-06-04 15:40:29 -06:00
func SSE(c echo.Context) error {
2023-05-18 20:04:55 -06:00
channel := c.QueryParam("channel")
if channel == "" {
channel = "default"
}
// Use the request context, which is cancelled when the client disconnects
ctx := c.Request().Context()
2024-06-04 15:40:29 -06:00
c.Response().Header().Set(echo.HeaderContentType, "text/event-stream")
c.Response().Header().Set(echo.HeaderConnection, "keep-alive")
c.Response().Header().Set(echo.HeaderCacheControl, "no-cache")
// Create a channel to receive messages from the lib.SSEServer
clientChan := make(chan string)
2023-05-18 20:04:55 -06:00
2024-06-04 15:40:29 -06:00
// Add the client to the lib.SSEServer
lib.SSEServer.AddClient(channel, clientChan)
2023-05-18 20:04:55 -06:00
2024-06-04 15:40:29 -06:00
defer func() {
// Remove the client from the lib.SSEServer when the connection is closed
lib.SSEServer.RemoveClient(channel, clientChan)
}()
2023-05-18 20:04:55 -06:00
2024-06-04 15:40:29 -06:00
// Create a ticker that fires every 15 seconds
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
2023-05-18 20:04:55 -06:00
for {
select {
case <-ctx.Done():
// If the client has disconnected, stop the loop
return nil
2024-06-04 15:40:29 -06:00
case <-ticker.C:
// Every 30 seconds, send a comment to keep the connection alive
if _, err := c.Response().Write([]byte(": keep-alive\n\n")); err != nil {
return err
}
c.Response().Flush()
case msg := <-clientChan:
// Handle incoming messages from the lib.SSEServer
data := fmt.Sprintf("data: %s\n\n", msg)
if _, err := c.Response().Write([]byte(data)); err != nil {
return err
}
c.Response().Flush()
2023-05-18 20:04:55 -06:00
}
}
}