Phase 4.0: WebSocket chat and danmaku system implemented
This commit is contained in:
51
backend/internal/api/chat_handler.go
Normal file
51
backend/internal/api/chat_handler.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gorilla/websocket"
|
||||
|
||||
"hightube/internal/chat"
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
return true // Allow all connections
|
||||
},
|
||||
}
|
||||
|
||||
// WSHandler handles websocket requests from clients
|
||||
func WSHandler(c *gin.Context) {
|
||||
roomID := c.Param("room_id")
|
||||
username := c.DefaultQuery("username", "Anonymous")
|
||||
|
||||
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
|
||||
if err != nil {
|
||||
fmt.Printf("[WS ERROR] Failed to upgrade: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
client := &chat.Client{
|
||||
Hub: chat.MainHub,
|
||||
Conn: conn,
|
||||
Send: make(chan []byte, 256),
|
||||
RoomID: roomID,
|
||||
Username: username,
|
||||
}
|
||||
|
||||
client.Hub.RegisterClient(client)
|
||||
|
||||
// Start reading and writing loops in goroutines
|
||||
go client.WritePump()
|
||||
go client.ReadPump()
|
||||
|
||||
// Optionally broadcast a system message: User Joined
|
||||
chat.MainHub.BroadcastToRoom(chat.Message{
|
||||
Type: "system",
|
||||
Username: "System",
|
||||
Content: fmt.Sprintf("%s joined the room", username),
|
||||
RoomID: roomID,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user