Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Louuie committed Dec 22, 2024
0 parents commit 3c6a14a
Show file tree
Hide file tree
Showing 5 changed files with 173 additions and 0 deletions.
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module gochat

go 1.23.3

require github.com/gorilla/websocket v1.5.3 // direct
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
23 changes: 23 additions & 0 deletions go_chat.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package main

import (
"fmt"
"gochat/page"
"gochat/ws"
)

func main() {
// Start WebSocket server
ws.StartServer(messageHandler)

// Start the static HTML Page
page.Start()

// Block main thread to keep server running
select {}
}

// Message handler processes messages from WebSocket clients
func messageHandler(message []byte) {
fmt.Printf("Reccieved %s\n", message)
}
93 changes: 93 additions & 0 deletions page/html.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package page

import (
"net/http"
)

func main() {
// Serve HTML frontend
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GoChat</title>
<script>
// Establish a WebSocket connection
const ws = new WebSocket("ws://localhost:8080/ws");
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.preventDefault();
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;
console.log(usernameInput);
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>');
}
};
</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="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>
<button type="submit">Send</button>
</form>
</div>
</body>
</html>
`))
})

// Start HTTP server on port 3030
http.ListenAndServe(":3030", nil)
}

func Start() {
main()
}
50 changes: 50 additions & 0 deletions ws/web_socket.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package ws

import (
"log"
"net/http"

"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}

type Server struct {
clients map[*websocket.Conn]bool
handleMessage func(message []byte)
}

func StartServer(handleMessage func(message []byte)) *Server {
server := Server{
make(map[*websocket.Conn]bool),
handleMessage,
}
http.HandleFunc("/ws", server.echo)
go http.ListenAndServe(":8080", nil)
return &server
}

func (server *Server) echo(w http.ResponseWriter, r *http.Request) {
conn, _ := upgrader.Upgrade(w, r, nil)
server.clients[conn] = true
for {
mt, msg, err := conn.ReadMessage()
if err != nil || mt == websocket.CloseMessage {
log.Fatalln(err)
}
go server.handleMessage(msg)
go server.WriteMessage(msg)
}
delete(server.clients, conn)
conn.Close()
}

func (server *Server) WriteMessage(message []byte) {
for conn := range server.clients {
conn.WriteMessage(websocket.TextMessage, message)
}
}

0 comments on commit 3c6a14a

Please sign in to comment.