sse.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package index
  2. import (
  3. "io"
  4. "time"
  5. "github.com/0xJacky/Nginx-UI/api"
  6. "github.com/0xJacky/Nginx-UI/internal/cache"
  7. "github.com/gin-gonic/gin"
  8. )
  9. // GetIndexStatus is an SSE endpoint that sends real-time index status updates
  10. func GetIndexStatus(c *gin.Context) {
  11. api.SetSSEHeaders(c)
  12. notify := c.Writer.CloseNotify()
  13. // Subscribe to scanner status changes
  14. statusChan := cache.SubscribeScanningStatus()
  15. // Ensure we unsubscribe when the handler exits
  16. defer cache.UnsubscribeScanningStatus(statusChan)
  17. // Main event loop
  18. for {
  19. select {
  20. case status, ok := <-statusChan:
  21. // If channel closed, exit
  22. if !ok {
  23. return
  24. }
  25. // Send status update
  26. c.Stream(func(w io.Writer) bool {
  27. c.SSEvent("message", gin.H{
  28. "scanning": status,
  29. })
  30. return false
  31. })
  32. case <-time.After(30 * time.Second):
  33. // Send heartbeat to keep connection alive
  34. c.Stream(func(w io.Writer) bool {
  35. c.SSEvent("heartbeat", "")
  36. return false
  37. })
  38. case <-notify:
  39. // Client disconnected
  40. return
  41. }
  42. }
  43. }