Creating a real-time chat application can be an excellent project for understanding WebSocket connections. WebSockets allow you to open an interactive session between a client and a server. In this article, we'll walk through the steps required to implement a real-time chat application using the Go programming language.
Setting Up the Project
To get started, let's create a new directory for the chat application project:
bash
$ mkdir go-chat
$ cd go-chat
Next, initialize a new Go module:
bash
$ go mod init go-chat
Installing Dependencies
We'll need the gorilla/websocket package for WebSocket support. Install the package with:
bash
$ go get github.com/gorilla/websocket
Creating the WebSocket Server
Now, let's implement a basic WebSocket server that will handle WebSocket connections, messages reception, and broadcasting.
go
package main
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func handleConnections(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println(err)
return
}
defer ws.Close()
for {
messageType, message, err := ws.ReadMessage()
if err != nil {
fmt.Println(err)
break
}
fmt.Printf("Received: %s\n", message)
if err := ws.WriteMessage(messageType, message); err != nil {
fmt.Println(err)
break
}
}
}
func main() {
fs := http.FileServer(http.Dir("./public"))
http.Handle("/", fs)
http.HandleFunc("/ws", handleConnections)
if err := http.ListenAndServe(":8080", nil); err != nil {
fmt.Println(err)
}
}
Frontend: Simple HTML and JavaScript Client
Let's create a simple HTML file with JavaScript to connect to our WebSocket server:
html
Go Chat
Real-Time Chat
Send
const ws = new WebSocket('ws://localhost:8080/ws');
ws.onmessage = function(event) {
const messages = document.getElementById('messages');
const message = document.createElement('li');
message.textContent = event.data;
messages.appendChild(message);
};
document.getElementById('sendBtn').onclick = function() {
const messageInput = document.getElementById('message');
ws.send(messageInput.value);
messageInput.value = '';
};
Running Your Chat Application
To run your chat application, you'll need to open a terminal and execute:
bash
$ go run .
You can access your chat application by opening a web browser and navigating to http://localhost:8080.
Conclusion
In this tutorial, we covered how to create a simple real-time chat application using Go and WebSockets. This is just the foundation, and you can further enhance it by adding features such as user authentication, private messaging, and chat rooms.