41 lines
874 B
Go
41 lines
874 B
Go
package models
|
|
|
|
import (
|
|
"context"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/coder/websocket"
|
|
)
|
|
|
|
type Channel struct {
|
|
ID string `json:"id"`
|
|
RoomName string `json:"room_name"`
|
|
TotalMessages int64 `json:"total_messages"`
|
|
Messages []Message
|
|
Mu sync.RWMutex
|
|
// Active listeners in specific channel
|
|
Clients map[*websocket.Conn]bool
|
|
}
|
|
|
|
type Message struct {
|
|
Content string `json:"content"`
|
|
Sender *User `json:"sender"`
|
|
Timestamp time.Time `json:"timestamp"`
|
|
}
|
|
|
|
func (c *Channel) Broadcast(ctx context.Context, msg Message) {
|
|
c.Mu.Lock()
|
|
defer c.Mu.Unlock()
|
|
|
|
// Save to history
|
|
c.Messages = append(c.Messages, msg)
|
|
c.TotalMessages++
|
|
|
|
// Send to all active WebSocket connections
|
|
for conn := range c.Clients {
|
|
payload := []byte(msg.Sender.Username + ": " + msg.Content)
|
|
_ = conn.Write(ctx, websocket.MessageText, payload)
|
|
}
|
|
}
|