This commit is contained in:
2024-01-17 12:02:03 -07:00
parent 161cc95538
commit f8ce4e3b48
43 changed files with 1614 additions and 21 deletions

11
api/ping.go Normal file
View File

@ -0,0 +1,11 @@
package api
import (
"net/http"
"github.com/labstack/echo/v4"
)
func Ping(c echo.Context) error {
return c.String(http.StatusOK, "Pong!")
}

58
api/sse.go Normal file
View File

@ -0,0 +1,58 @@
package api
import (
"fmt"
"log"
"time"
"github.com/labstack/echo/v4"
"goth.stack/lib"
)
func SSEDemo(c echo.Context) error {
channel := c.QueryParam("channel")
if channel == "" {
channel = "default"
}
// Use the request context, which is cancelled when the client disconnects
ctx := c.Request().Context()
pubsub, _ := lib.Subscribe(lib.RedisClient, channel)
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)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
// If the client has disconnected, stop the loop
return nil
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()
default:
// Handle incoming messages as before
msg, err := pubsub.ReceiveMessage(ctx)
if err != nil {
log.Printf("Failed to receive message: %v", err)
continue
}
data := fmt.Sprintf("data: %s\n\n", msg.Payload)
if _, err := c.Response().Write([]byte(data)); err != nil {
return err
}
c.Response().Flush()
}
}
}

37
api/ssedemosend.go Normal file
View File

@ -0,0 +1,37 @@
package api
import (
"net/http"
"github.com/labstack/echo/v4"
"goth.stack/lib"
)
func SSEDemoSend(c echo.Context) error {
channel := c.QueryParam("channel")
if channel == "" {
channel = "default"
}
// Get message from query parameters, form value, or request body
message := c.QueryParam("message")
if message == "" {
message = c.FormValue("message")
if message == "" {
var body map[string]string
if err := c.Bind(&body); err != nil {
return err
}
message = body["message"]
}
}
if message == "" {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "message parameter is required"})
}
// Send message
lib.SendSSE("default", message)
return c.JSON(http.StatusOK, map[string]string{"status": "message sent"})
}