Template
1
0
Fork 0
goth.stack/api/sse.go

70 lines
1.8 KiB
Go
Raw 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-11-03 17:01:48 -06:00
"goth.stack/lib"
2023-05-18 20:04:55 -06:00
)
2024-10-20 16:16:50 -06:00
// SSE godoc
// @Summary Server-Sent Events endpoint
// @Description Establishes a Server-Sent Events connection
// @Tags sse
// @Accept json
// @Produce text/event-stream
// @Param channel query string false "Channel name"
// @Success 200 {string} string "Event stream"
// @Router /sse [get]
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
}
}
}