Template
1
0
Fork 0
goth.stack/lib/sse.go

67 lines
1.3 KiB
Go
Raw Normal View History

2023-05-18 20:04:55 -06:00
package lib
2024-06-04 15:40:29 -06:00
import "sync"
2023-05-18 20:04:55 -06:00
type SSEServerType struct {
clients map[string]map[chan string]bool
mu sync.Mutex
}
var SSEServer *SSEServerType
func init() {
SSEServer = &SSEServerType{
clients: make(map[string]map[chan string]bool),
}
}
func NewSSEServer() *SSEServerType {
return &SSEServerType{
clients: make(map[string]map[chan string]bool),
}
}
func (s *SSEServerType) AddClient(channel string, client chan string) {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.clients[channel]; !ok {
s.clients[channel] = make(map[chan string]bool)
}
s.clients[channel][client] = true
2024-06-04 15:40:29 -06:00
LogInfo.Printf("\nClient connected to channel %s\n", channel)
2023-05-18 20:04:55 -06:00
}
func (s *SSEServerType) RemoveClient(channel string, client chan string) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.clients[channel], client)
if len(s.clients[channel]) == 0 {
delete(s.clients, channel)
}
2024-06-04 15:40:29 -06:00
LogInfo.Printf("\nClient disconnected from channel %s\n", channel)
2023-05-18 20:04:55 -06:00
}
func (s *SSEServerType) ClientCount(channel string) int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.clients[channel])
}
2024-06-04 16:07:13 -06:00
func (s *SSEServerType) SendSSE(channel string, message string) {
s.mu.Lock()
defer s.mu.Unlock()
2023-05-18 20:04:55 -06:00
2024-06-04 16:07:13 -06:00
go func() {
for client := range s.clients[channel] {
client <- message
}
}()
2023-05-18 20:04:55 -06:00
2024-06-04 15:40:29 -06:00
LogDebug.Printf("\nMessage broadcast on channel %s: %s\n", channel, message)
2023-05-18 20:04:55 -06:00
}