Incoming message handling fix

This commit is contained in:
Atridad Lahiji 2024-05-06 01:23:05 -06:00
parent ec04d36559
commit 7463d1a252
No known key found for this signature in database

View file

@ -90,14 +90,25 @@ func SetSSEHeaders(c echo.Context) {
} }
func HandleIncomingMessages(c echo.Context, pubsub pubsub.PubSubMessage, client chan string) { func HandleIncomingMessages(c echo.Context, pubsub pubsub.PubSubMessage, client chan string) {
// Create a new context that is not tied to the client's request context
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // Cancel the context when the function returns
// Use a separate goroutine to monitor the client's request context
go func() {
<-c.Request().Context().Done()
cancel() // Cancel the context when the client disconnects
}()
for { for {
select { select {
case <-c.Request().Context().Done(): case <-ctx.Done():
// The client has disconnected. Stop trying to send messages. // The context has been canceled, either by the client disconnecting
// or by the function returning. Stop trying to send messages.
return return
default: default:
// The client is still connected. Continue processing messages. // The client is still connected. Continue processing messages.
msg, err := pubsub.ReceiveMessage(c.Request().Context()) msg, err := pubsub.ReceiveMessage(ctx)
if err != nil { if err != nil {
log.Printf("Failed to receive message: %v", err) log.Printf("Failed to receive message: %v", err)
return return