2023-09-07 21:23:51 -06:00
|
|
|
package handler
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/fastenhealth/fasten-onprem/backend/pkg"
|
2023-09-07 22:13:40 -06:00
|
|
|
"github.com/fastenhealth/fasten-onprem/backend/pkg/web/sse"
|
2023-09-07 21:23:51 -06:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"io"
|
2023-09-08 12:27:38 -06:00
|
|
|
"log"
|
2023-09-07 21:23:51 -06:00
|
|
|
)
|
|
|
|
|
|
|
|
// SSEStream is a handler for the server sent event stream (notifications from background processes)
|
|
|
|
// see: https://github.com/gin-gonic/examples/blob/master/server-sent-event/main.go
|
|
|
|
// see: https://stackoverflow.com/questions/66327142/selectively-send-event-to-particular-clients
|
|
|
|
//
|
|
|
|
// test using:
|
|
|
|
// curl -N -H "Authorization: Bearer xxxxx" http://localhost:9090/api/secure/sse/stream
|
|
|
|
func SSEStream(c *gin.Context) {
|
|
|
|
|
|
|
|
//logger := c.MustGet(pkg.ContextKeyTypeLogger).(*logrus.Entry)
|
|
|
|
//databaseRepo := c.MustGet(pkg.ContextKeyTypeDatabase).(database.DatabaseRepository)
|
|
|
|
v, ok := c.Get(pkg.ContextKeyTypeSSEClientChannel)
|
|
|
|
if !ok {
|
2023-09-08 12:27:38 -06:00
|
|
|
log.Printf("could not get client channel from context")
|
2023-09-07 21:23:51 -06:00
|
|
|
return
|
|
|
|
}
|
2023-09-08 12:27:38 -06:00
|
|
|
listener, ok := v.(sse.EventBusListener)
|
2023-09-07 21:23:51 -06:00
|
|
|
if !ok {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
c.Stream(func(w io.Writer) bool {
|
|
|
|
// Stream message to client from message channel
|
2023-09-08 12:27:38 -06:00
|
|
|
if msg, ok := <-listener.ResponseChan; ok {
|
2023-09-07 21:23:51 -06:00
|
|
|
c.SSEvent("message", msg)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
})
|
|
|
|
}
|