live.go 1010 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package notification
  2. import (
  3. "github.com/0xJacky/Nginx-UI/internal/notification"
  4. "github.com/0xJacky/Nginx-UI/model"
  5. "github.com/gin-gonic/gin"
  6. "io"
  7. "time"
  8. )
  9. func Live(c *gin.Context) {
  10. c.Header("Content-Type", "text/event-stream")
  11. c.Header("Cache-Control", "no-cache")
  12. c.Header("Connection", "keep-alive")
  13. // https://stackoverflow.com/questions/27898622/server-sent-events-stopped-work-after-enabling-ssl-on-proxy/27960243#27960243
  14. c.Header("X-Accel-Buffering", "no")
  15. evtChan := make(chan *model.Notification)
  16. notification.SetClient(c, evtChan)
  17. notify := c.Writer.CloseNotify()
  18. c.Stream(func(w io.Writer) bool {
  19. c.SSEvent("heartbeat", "")
  20. return false
  21. })
  22. for {
  23. select {
  24. case n := <-evtChan:
  25. c.Stream(func(w io.Writer) bool {
  26. c.SSEvent("message", n)
  27. return false
  28. })
  29. case <-time.After(30 * time.Second):
  30. c.Stream(func(w io.Writer) bool {
  31. c.SSEvent("heartbeat", "")
  32. return false
  33. })
  34. case <-notify:
  35. notification.RemoveClient(c)
  36. return
  37. }
  38. }
  39. }