notification.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package notification
  2. import (
  3. "github.com/0xJacky/Nginx-UI/model"
  4. "github.com/0xJacky/Nginx-UI/query"
  5. "github.com/gin-gonic/gin"
  6. "github.com/uozi-tech/cosy/logger"
  7. "sync"
  8. )
  9. var (
  10. clientMap = make(map[*gin.Context]chan *model.Notification)
  11. mutex = &sync.RWMutex{}
  12. )
  13. func SetClient(c *gin.Context, evtChan chan *model.Notification) {
  14. mutex.Lock()
  15. defer mutex.Unlock()
  16. clientMap[c] = evtChan
  17. }
  18. func RemoveClient(c *gin.Context) {
  19. mutex.Lock()
  20. defer mutex.Unlock()
  21. close(clientMap[c])
  22. delete(clientMap, c)
  23. }
  24. func Info(title string, details string) {
  25. push(model.NotificationInfo, title, details)
  26. }
  27. func Error(title string, details string) {
  28. push(model.NotificationError, title, details)
  29. }
  30. func Warning(title string, details string) {
  31. push(model.NotificationWarning, title, details)
  32. }
  33. func Success(title string, details string) {
  34. push(model.NotificationSuccess, title, details)
  35. }
  36. func push(nType model.NotificationType, title string, details string) {
  37. n := query.Notification
  38. data := &model.Notification{
  39. Type: nType,
  40. Title: title,
  41. Details: details,
  42. }
  43. err := n.Create(data)
  44. if err != nil {
  45. logger.Error(err)
  46. return
  47. }
  48. broadcast(data)
  49. }
  50. func broadcast(data *model.Notification) {
  51. mutex.RLock()
  52. defer mutex.RUnlock()
  53. for _, evtChan := range clientMap {
  54. evtChan <- data
  55. }
  56. }