@@ -0,0 +1,30 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"shagram/internal/api"
|
||||
"shagram/internal/db"
|
||||
"shagram/internal/websocket"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func main() {
|
||||
database, err := db.NewDB("shagram.db")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
hub := websocket.NewHub()
|
||||
router := gin.Default()
|
||||
|
||||
router.GET("/ws/:room", api.WebSocketHandler(hub))
|
||||
router.GET("/api/rooms", func(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"rooms": "TODO"})
|
||||
})
|
||||
router.Static("/static", "./static")
|
||||
router.GET("/", func(c *gin.Context) {
|
||||
c.File("./static/index.html")
|
||||
})
|
||||
router.Run(":8080")
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"shagram/internal/websocket"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
gws "github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
var upgrader = gws.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool { return true },
|
||||
}
|
||||
|
||||
func WebSocketHandler(hub *websocket.Hub) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
roomID := c.Param("room")
|
||||
room := hub.GetOrCreateRoom(roomID)
|
||||
|
||||
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
client := &websocket.Client{Conn: conn, Room: room}
|
||||
room.Register(client)
|
||||
|
||||
go func() {
|
||||
defer func() {
|
||||
room.Unregister(client)
|
||||
hub.CleanupRoom(roomID)
|
||||
}()
|
||||
|
||||
for {
|
||||
var msg map[string]string
|
||||
err := client.Conn.ReadJSON(&msg)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
message := []byte(msg["text"])
|
||||
room.Broadcast(message)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -17,7 +17,7 @@ func NewDB(path string) (*DB, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
schema, err := os.ReadFile("../../migrations/schema.sql")
|
||||
schema, err := os.ReadFile("migrations/schema.sql")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@ package websocket
|
||||
import "github.com/gorilla/websocket"
|
||||
|
||||
type Client struct {
|
||||
conn *websocket.Conn
|
||||
room *Room
|
||||
Conn *websocket.Conn
|
||||
Room *Room
|
||||
}
|
||||
|
||||
type Room struct {
|
||||
@@ -25,12 +25,12 @@ func (r *Room) Register(client *Client) {
|
||||
|
||||
func (r *Room) Unregister(client *Client) {
|
||||
delete(r.clients, client)
|
||||
client.conn.Close()
|
||||
client.Conn.Close()
|
||||
}
|
||||
|
||||
func (r *Room) Broadcast(message []byte) {
|
||||
for client := range r.clients {
|
||||
err := client.conn.WriteMessage(websocket.TextMessage, message)
|
||||
err := client.Conn.WriteMessage(websocket.TextMessage, message)
|
||||
if err != nil {
|
||||
r.Unregister(client)
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
BIN
Binary file not shown.
@@ -0,0 +1,44 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Shagram Chat</title>
|
||||
<style>
|
||||
body { font-family: Arial; margin: 20px; }
|
||||
#messages {
|
||||
height: 300px;
|
||||
border: 1px solid #ccc;
|
||||
overflow-y: auto;
|
||||
padding: 10px;
|
||||
margin-bottom: 10px;
|
||||
background: #f9f9f9;
|
||||
}
|
||||
.message {
|
||||
margin: 5px 0;
|
||||
padding: 8px;
|
||||
background: #e3f2fd;
|
||||
border-radius: 5px;
|
||||
border-left: 3px solid #2196F3;
|
||||
}
|
||||
input { padding: 8px; width: 300px; }
|
||||
button { padding: 8px 15px; cursor: pointer; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>📱 Shagram Chat</h1>
|
||||
|
||||
<div>
|
||||
<input type="text" id="roomInput" placeholder="Room name" value="general">
|
||||
<button onclick="connectRoom()">Connect</button>
|
||||
</div>
|
||||
|
||||
<div id="messages"></div>
|
||||
|
||||
<div>
|
||||
<input type="text" id="messageInput" placeholder="Type message..."
|
||||
onkeypress="if(event.key==='Enter') sendMessage()">
|
||||
<button onclick="sendMessage()">Send</button>
|
||||
</div>
|
||||
|
||||
<script src="/static/js/chat.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,43 @@
|
||||
let ws = null;
|
||||
const messagesDiv = document.getElementById('messages');
|
||||
const messageInput = document.getElementById('messageInput');
|
||||
const roomInput = document.getElementById('roomInput');
|
||||
|
||||
function connectRoom() {
|
||||
const room = roomInput.value || 'general';
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
ws = new WebSocket(`${protocol}//localhost:8080/ws/${room}`);
|
||||
|
||||
ws.onopen = function() {
|
||||
console.log('Connected to room: ' + room);
|
||||
messagesDiv.innerHTML = '<div class="message">✅ Connected to ' + room + '</div>';
|
||||
};
|
||||
|
||||
ws.onmessage = function(event) {
|
||||
const msgDiv = document.createElement('div');
|
||||
msgDiv.className = 'message';
|
||||
msgDiv.textContent = event.data;
|
||||
messagesDiv.appendChild(msgDiv);
|
||||
messagesDiv.scrollTop = messagesDiv.scrollHeight;
|
||||
};
|
||||
|
||||
ws.onerror = function(error) {
|
||||
console.error('WebSocket error:', error);
|
||||
messagesDiv.innerHTML += '<div class="message">❌ Error: ' + error + '</div>';
|
||||
};
|
||||
|
||||
ws.onclose = function() {
|
||||
messagesDiv.innerHTML += '<div class="meassage">⛔ Disconnected</div>';
|
||||
};
|
||||
}
|
||||
|
||||
function sendMessage() {
|
||||
const text = messageInput.value.trim();
|
||||
if (!text || !ws || ws.readyState !== WebSocket.OPEN) {
|
||||
alert('Not connected or empty message');
|
||||
return;
|
||||
}
|
||||
|
||||
ws.send(JSON.stringify({text: text}));
|
||||
messageInput.value = '';
|
||||
}
|
||||
Reference in New Issue
Block a user