This commit is contained in:
2024-01-26 14:39:58 -07:00
parent d84eaeb9ca
commit 983c11a162
10 changed files with 95 additions and 116 deletions

View File

@ -3,28 +3,26 @@ package api
import (
"fmt"
"log"
"net/http"
"time"
"github.com/uptrace/bunrouter"
"github.com/labstack/echo/v4"
"goth.stack/lib"
)
func SSE(w http.ResponseWriter, req bunrouter.Request) error {
queryParams := req.URL.Query()
channel := queryParams.Get("channel")
func SSE(c echo.Context) error {
channel := c.QueryParam("channel")
if channel == "" {
channel = "default"
}
// Use the request context, which is cancelled when the client disconnects
ctx := req.Context()
ctx := c.Request().Context()
pubsub, _ := lib.Subscribe(lib.RedisClient, channel)
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Cache-Control", "no-cache")
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 ticker that fires every 15 seconds
ticker := time.NewTicker(30 * time.Second)
@ -37,10 +35,10 @@ func SSE(w http.ResponseWriter, req bunrouter.Request) error {
return nil
case <-ticker.C:
// Every 30 seconds, send a comment to keep the connection alive
if _, err := w.Write([]byte(": keep-alive\n\n")); err != nil {
if _, err := c.Response().Write([]byte(": keep-alive\n\n")); err != nil {
return err
}
w.(http.Flusher).Flush()
c.Response().Flush()
default:
// Handle incoming messages as before
msg, err := pubsub.ReceiveMessage(ctx)
@ -50,11 +48,11 @@ func SSE(w http.ResponseWriter, req bunrouter.Request) error {
}
data := fmt.Sprintf("data: %s\n\n", msg.Payload)
if _, err := w.Write([]byte(data)); err != nil {
if _, err := c.Response().Write([]byte(data)); err != nil {
return err
}
w.(http.Flusher).Flush()
c.Response().Flush()
}
}
}