How to Create a Real-Time Chat App in Go with WebSockets
Learn how to create a real-time chat app using Go (Golang) and WebSockets. This Go tutorial covers connection setup, broadcast messaging and handling events.
- Home
- Development Tutorial
- How to Create a Real-Time Chat App in Go with WebSockets
Partner With APPECODE! Let’s Work Together!
Let APPECODE implement your vision and take your project from idea to done.
How to Create a Real-Time Chat App in Go with WebSockets
This hands-on development tutorial teaches you how to create a scalable real-time chat application using Go and WebSockets. With Go’s built-in concurrency model, you’ll learn how to manage multiple connections efficiently and create a responsive chat experience with minimal latency.
Let’s begin.
Tutorial Information
This tutorial assumes you already have an applicable development environment set up.
This hands-on tutorial teaches you how to create a scalable real-time chat application using Go and WebSockets. With Go’s built-in concurrency model, you’ll learn how to manage multiple connections efficiently and create a responsive chat experience with minimal latency.
What are WebSockets and Why Use Go?
WebSockets are a communication protocol that provides full-duplex, bidirectional connections between clients and servers over a single TCP connection. Unlike traditional HTTP, which requires a new connection for each request-response cycle, WebSockets keep the connection open, making them ideal for real-time applications like chat apps, games, and live data feeds. Go is an excellent choice for building WebSocket servers because of its efficient concurrency model powered by goroutines and channels. This makes it easy to manage multiple client connections simultaneously without writing complex multithreaded code.Prerequisites
- Go installed on your system: Download Go
- Basic knowledge of Go syntax
- A terminal and a code editor like VS Code or GoLand
Step 1: Create Your Project Directory
Open your terminal and create a folder namedgo-chat
. Navigate into it and initialize a Go module:
mkdir go-chat
cd go-chat
go mod init go-chat
This sets up your Go project with module support so you can import packages cleanly.
Step 2: Install Gorilla WebSocket Package
You’ll use the Gorilla WebSocket package for handling WebSocket connections. In the terminal, run:go get github.com/gorilla/websocket
This downloads and adds the package to your project dependencies.
Step 3: Create the Main Server File
Create a file calledmain.go
in the root of your project and paste in the following code:
package main
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
var clients = make(map[*websocket.Conn]bool)
var broadcast = make(chan string)
func handleConnections(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println("Upgrade error:", err)
return
}
defer ws.Close()
clients[ws] = true
for {
var msg string
err := ws.ReadJSON(&msg)
if err != nil {
delete(clients, ws)
break
}
broadcast <- msg
}
}
func handleMessages() {
for {
msg := <-broadcast
for client := range clients {
err := client.WriteJSON(msg)
if err != nil {
client.Close()
delete(clients, client)
}
}
}
}
func main() {
http.HandleFunc("/ws", handleConnections)
go handleMessages()
fmt.Println("Server started on :8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println("Server error:", err)
}
}
This code sets up an HTTP server that upgrades requests to WebSocket connections, receives messages, and broadcasts them to all clients. It uses Go’s channels and goroutines to handle messages concurrently.
Step 4: Run the Server
In the terminal, run:go run main.go
Your server is now running on http://localhost:8080/ws
. You can test it using a WebSocket client like Postman or a custom frontend.
Step 5: Create a Simple HTML Frontend (Optional)
If you want to test it in the browser, create a file namedindex.html
and paste this inside:
<!DOCTYPE html>
<html>
<head><title>Go Chat</title></head>
<body>
<input id="msg" type="text" />
<button onclick="sendMessage()">Send</button>
<ul id="messages"></ul>
<script>
const socket = new WebSocket("ws://localhost:8080/ws");
socket.onmessage = function(event) {
const li = document.createElement("li");
li.textContent = event.data;
document.getElementById("messages").appendChild(li);
};
function sendMessage() {
const input = document.getElementById("msg");
socket.send(JSON.stringify(input.value));
input.value = "";
}
</script>
</body>
</html>
Open this file in a browser to test sending and receiving chat messages with the Go WebSocket server.
Conclusion
You’ve now built a fully functional real-time chat server in Go using WebSockets. You learned how to manage connections, broadcast messages, and use Go’s concurrency model to create a scalable, responsive backend. This is a great foundation to add features like user IDs, message timestamps, persistent storage, and even private rooms.Team APPECODE
This concludes this APPECODE development tutorial. Thanks for coding with us today. You now have the tools and techniques to apply the demonstrated skills in real development scenarios. Whether you’re refining a feature or launching something big, APPECODE is here to guide your technical journey every step of the way. Team APPECODE is all about helping devs like you grow with real-world, hands-on examples. Have questions or project ideas? Let’s keep the conversation going—your next big breakthrough could be one line away.