This commit is contained in:
Cereska
2026-03-02 08:47:52 -05:00
parent a1b599d030
commit 661011485c
7 changed files with 184 additions and 42 deletions

View File

@@ -1,8 +1,11 @@
package models
import (
"context"
"sync"
"time"
"github.com/coder/websocket"
)
type Channel struct {
@@ -10,21 +13,28 @@ type Channel struct {
RoomName string `json:"room_name"`
TotalMessages int64 `json:"total_messages"`
Messages []Message
mu sync.RWMutex
Mu sync.RWMutex
// Active listeners in specific channel
Clients map[*websocket.Conn]bool
}
type Message struct {
Content string
Sender *User
Timestamp time.Time
Content string `json:"content"`
Sender *User `json:"sender"`
Timestamp time.Time `json:"timestamp"`
}
// Methods for channel
func (c *Channel) Send(msg Message) {
// Lock write
c.mu.Lock()
defer c.mu.Unlock()
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)
}
}