live.go 869 B

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