live.go 779 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package notification
  2. import (
  3. "github.com/0xJacky/Nginx-UI/api"
  4. "github.com/0xJacky/Nginx-UI/internal/notification"
  5. "github.com/0xJacky/Nginx-UI/model"
  6. "github.com/gin-gonic/gin"
  7. "io"
  8. "time"
  9. )
  10. func Live(c *gin.Context) {
  11. api.SetSSEHeaders(c)
  12. evtChan := make(chan *model.Notification)
  13. notification.SetClient(c, evtChan)
  14. notify := c.Writer.CloseNotify()
  15. c.Stream(func(w io.Writer) bool {
  16. c.SSEvent("heartbeat", "")
  17. return false
  18. })
  19. for {
  20. select {
  21. case n := <-evtChan:
  22. c.Stream(func(w io.Writer) bool {
  23. c.SSEvent("message", n)
  24. return false
  25. })
  26. case <-time.After(30 * time.Second):
  27. c.Stream(func(w io.Writer) bool {
  28. c.SSEvent("heartbeat", "")
  29. return false
  30. })
  31. case <-notify:
  32. notification.RemoveClient(c)
  33. return
  34. }
  35. }
  36. }