Skip to content

Commit

Permalink
UUID now works with the chat through the sockets query
Browse files Browse the repository at this point in the history
  • Loading branch information
Louuie committed Dec 24, 2024
1 parent 8dfa470 commit d94cdfc
Show file tree
Hide file tree
Showing 3 changed files with 118 additions and 37 deletions.
2 changes: 1 addition & 1 deletion fiber/db/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func CreateTable(db *sql.DB) error {
return nil
}
func CreateRoom(db *sql.DB, UUID string) (string, int, error) {
var room_nuber = 1
var room_nuber = 2
_, err := db.Exec("INSERT into rooms VALUES ($1, $2)", UUID, room_nuber)
if err, ok := err.(*pq.Error); ok {
// 23505: unique_violation
Expand Down
146 changes: 111 additions & 35 deletions page/htmx.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,45 +18,121 @@ func main() {
<title>GoChat</title>
<script src="https://unpkg.com/[email protected]"></script>
<script>
document.addEventListener("htmx:afterSwap", (event) => {
// Check if the swap target was the #rooms-container
if (event.detail.target.id === "rooms-container") {
// Attach click event listener to each button
const buttons = document.querySelectorAll(".room-btn");
buttons.forEach((button) => {
button.addEventListener("click", () => {
// Extract the UUID from the clicked button
const uuid = button.getAttribute("data-uuid");
console.log("Room UUID clicked:", uuid);
// Open a WebSocket connection for the clicked UUID
const ws = new WebSocket('ws://localhost:8080/ws?uuid=${uuid}');
ws.onopen = () => {
console.log('WebSocket connection opened for UUID: ${uuid}');
};
ws.onmessage = (event) => {
console.log('Message from server: ${event.data}');
};
ws.onclose = () => {
console.log('WebSocket connection closed for UUID: ${uuid}');
};
});
});
}
});
</script>
// Establish a WebSocket connection
const ws = new WebSocket("ws://localhost:8080/ws?uuid=some-uuid");
let lastSentMessage = ""; // Store the last message sent by the client
// Handle username submission
function handleUsername(event) {
event.preventDefault(); // Prevent the form from refreshing the page
// Get the username input and chat elements
const usernameInput = document.getElementById("username-input");
const wholeChat = document.getElementById("whole-chat");
const usernameForm = document.getElementById("username-form");
// Check if the username is valid
if (usernameInput.value.trim() !== "") {
wholeChat.style.visibility = "visible"; // Show the chat interface
usernameForm.style.visibility = "hidden"; // Hide the username form
}
}
// Handle sending a message
function sendMessage(event) {
event.preventDefault(); // Prevent form submission default behavior
const input = document.getElementById("messageInput");
const message = input.value.trim();
if (message !== "") {
ws.send(message); // Send the message to the server
lastSentMessage = message; // Store the message
const chatDiv = document.getElementById("chat");
const usernameInput = document.getElementById("username-input").value;
chatDiv.insertAdjacentHTML(
"beforeend",
'<div>${usernameInput}: ${message}</div>'
); // Display the user's message
input.value = ""; // Clear the input field
}
}
// Handle incoming messages
ws.onmessage = (event) => {
const chatDiv = document.getElementById("chat");
// Avoid displaying duplicate messages
if (event.data !== lastSentMessage) {
chatDiv.insertAdjacentHTML(
"beforeend",
'<div>Other: ${event.data}</div>'
);
}
};
// Handle dynamic content loaded via HTMX
document.addEventListener("htmx:afterSwap", (event) => {
// Check if the swap target was the #rooms-container
if (event.detail.target.id === "rooms-container") {
// Attach click event listener to each button
const buttons = document.querySelectorAll(".room-btn");
buttons.forEach((button) => {
button.addEventListener("click", () => {
// Extract the UUID from the clicked button
const uuid = button.getAttribute("data-uuid");
console.log("Room UUID clicked:", uuid);
// Open a WebSocket connection for the clicked UUID
const ws = new WebSocket('ws://localhost:8080/ws?uuid=${uuid}');
// Define sendMessage function specific to this WebSocket
function sendMessage(event) {
event.preventDefault(); // Prevent form submission default behavior
const input = document.getElementById("messageInput");
const message = input.value.trim();
if (message !== "") {
ws.send(message); // Send the message to the server
const chatDiv = document.getElementById("chat");
const usernameInput = document.getElementById("username-input").value;
chatDiv.insertAdjacentHTML(
"beforeend",
'<div>${usernameInput}: ${message}</div>'
); // Display the user's message
input.value = ""; // Clear the input field
}
}
// Handle incoming messages from the WebSocket
ws.onmessage = (event) => {
const chatDiv = document.getElementById("chat");
// Avoid displaying duplicate messages
if (event.data !== lastSentMessage) {
chatDiv.insertAdjacentHTML(
"beforeend",
'<div>Other: ${event.data}</div>'
);
}
};
// Attach the sendMessage logic to the send button
document
.getElementById("sendButton")
.addEventListener("click", sendMessage);
});
});
}
});
</script>
</head>
<body>
<h1>GoChat</h1>
<form onsubmit="handleUsername(event)" id="username-form">
<input type="text" id="username-input" placeholder="Type your username" required>
<button type="submit">Send</button>
</form>
<div id="whole-chat" style="visibility: hidden;">
<div id="whole-chat">
<div id="chat" style="border: 1px solid #ccc; padding: 10px; height: 300px; overflow-y: scroll;"></div>
<form onsubmit="sendMessage(event)">
<input type="text" id="messageInput" placeholder="Type your message" required>
Expand Down
7 changes: 6 additions & 1 deletion ws/web_socket.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,12 @@ func (server *Server) echo(w http.ResponseWriter, r *http.Request) {
if err != nil {
log.Fatalln(err)
}
var chatUUID = "42fsqg-kl42fe"
params := r.URL.Query()
var chatUUID = params.Get("uuid")
if chatUUID == "" {
go server.WriteMessage([]byte("UUID is empty, closing connection"))
conn.Close()
}
server.UUID[chatUUID] = "1"
server.clients[conn] = true
for {
Expand Down

0 comments on commit d94cdfc

Please sign in to comment.