-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotification.go
74 lines (59 loc) · 1.94 KB
/
notification.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package middlewares
import (
"context"
"net/http"
"sync"
)
type contextKey string
const notificationKey contextKey = "notifications"
// Notification struct to hold categorized messages with severity
type Notification struct {
Category string
Message string
Severity string
}
var (
globalNotifications []Notification
notificationsMutex sync.Mutex
)
// AddGlobalNotification adds a notification to the global list and triggers SSE
func AddGlobalNotification(sseServer *SSEServer, category, message, severity string) {
notificationsMutex.Lock()
defer notificationsMutex.Unlock()
notification := Notification{
Category: category,
Message: message,
Severity: severity,
}
globalNotifications = append(globalNotifications, notification)
// Trigger SSE notification
if sseServer != nil {
sseMessage := formatNotificationMessage(notification)
sseServer.NotifyAll(sseMessage)
}
}
// Formats the notification message for SSE
func formatNotificationMessage(notification Notification) string {
return notification.Category + ": " + notification.Message + " (" + notification.Severity + ")"
}
// NotificationMiddleware to attach notifications to the request context
func NotificationMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
notifications := []Notification{}
// Lock the mutex and add global notifications
notificationsMutex.Lock()
notifications = append(notifications, globalNotifications...)
notificationsMutex.Unlock()
// Store the notifications in the request context
ctx := context.WithValue(r.Context(), notificationKey, notifications)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// GetNotificationsFromContext retrieves the notifications from the request context
func GetNotificationsFromContext(r *http.Request) []Notification {
notifications, ok := r.Context().Value(notificationKey).([]Notification)
if !ok {
return nil
}
return notifications
}