TechBuzzPro

Build a Real-Time Chat App with Go: Step-by-Step

· 6 min read · Apps & Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

You can build a real-time chat app with Go by using the standard library's HTTP server and the Gorilla WebSocket package to handle persistent connections. The core idea is simple: upgrade an HTTP connection to a WebSocket, keep a registry of connected clients, and broadcast every incoming message to all of them. This guide walks through a minimal but working implementation, then covers the mistakes that trip people up and how to fix them.

What You'll Need

  • Go installed (version 1.18 or later is fine; the code uses no version-specific features).
  • A code editor and a terminal.
  • Basic familiarity with Go syntax and HTTP handlers.
  • No database is required for this example—messages live in memory only.

Step-by-Step

  1. Create the project folder and initialise a module. In your terminal, run mkdir go-chat && cd go-chat, then go mod init chat. This creates a go.mod file so Go can track dependencies.
  2. Add the WebSocket library. Run go get github.com/gorilla/websocket. The Gorilla package is the de facto standard for WebSockets in Go and is well maintained. (The golang.org/x/net/websocket package exists but is older and less flexible; Gorilla is the safer choice.)
  3. Write the main server file. Create main.go with three parts: an HTTP handler that upgrades the connection, a client registry, and a broadcast loop. Start with the upgrade handler:
    var upgrader = websocket.Upgrader{
        CheckOrigin: func(r *http.Request) bool { return true },
    }
    
    func handleConn(w http.ResponseWriter, r *http.Request) {
        conn, err := upgrader.Upgrade(w, r, nil)
        if err != nil {
            log.Println(err)
            return
        }
        // register and read loop go here
    }
    The CheckOrigin function is set to allow all origins for local development. In production, restrict it to your own domain—see Common Mistakes.
  4. Create a client registry. Use a map protected by a mutex, or a channel-based hub. A simple mutex version:
    var (
        clients   = make(map[*websocket.Conn]bool)
        broadcast = make(chan []byte)
        mu        sync.Mutex
    )
    
    func handleMessages() {
        for {
            msg := <-broadcast
            mu.Lock()
            for client := range clients {
                err := client.WriteMessage(websocket.TextMessage, msg)
                if err != nil {
                    client.Close()
                    delete(clients, client)
                }
            }
            mu.Unlock()
        }
    }
    This loop reads from the broadcast channel and writes to every connected client. Deleting failed connections prevents dead sockets from piling up.
  5. Wire up the read loop. Inside handleConn, after upgrading, add the connection to the map and start reading:
    mu.Lock()
    clients[conn] = true
    mu.Unlock()
    
    defer func() {
        mu.Lock()
        delete(clients, conn)
        mu.Unlock()
        conn.Close()
    }()
    
    for {
        _, msg, err := conn.ReadMessage()
        if err != nil {
            break
        }
        broadcast <- msg
    }
    The deferred cleanup runs when the client disconnects, removing it from the registry.
  6. Serve a static HTML page. Create a public/index.html with a simple form and a <div id="messages">. Add JavaScript that opens a WebSocket to ws://localhost:8080/ws, appends incoming messages to the div, and sends the input value on form submit. Use new WebSocket(...) and listen for the onmessage event. This is the only client-side code you need.
  7. Register routes and start the server. In main, add:
    http.HandleFunc("/ws", handleConn)
    http.Handle("/", http.FileServer(http.Dir("./public")))
    go handleMessages()
    log.Fatal(http.ListenAndServe(":8080", nil))
    Run go run main.go and open http://localhost:8080 in two browser tabs. Type in one tab and the message should appear in both.
  8. Test the disconnect path. Close one tab. The server's read loop should hit an error, break, and run the deferred cleanup. Check the server logs to confirm no panic. If the map still holds the closed connection, your cleanup is not running—verify the defer is placed after the upgrade succeeds.

Common Mistakes

Forgetting to lock the map. Go maps are not safe for concurrent writes. If two goroutines add or delete clients at the same time, the program panics with "concurrent map writes." Always wrap map access in a mutex or use a single goroutine that owns the map and communicates via channels.

Leaving CheckOrigin wide open. Returning true for every origin works locally but allows any website to open a WebSocket to your server. In production, compare r.Header.Get("Origin") against an allowlist and return false otherwise.

Writing to a connection from multiple goroutines. Gorilla WebSocket connections do not support concurrent writers. All writes should go through the single broadcast loop, or you must add a per-connection mutex. Mixing direct writes from handlers with the broadcast loop causes corrupted frames.

Ignoring slow clients. A client on a poor connection can block the broadcast loop while its buffer fills. Use a buffered send channel per client and drop messages (or disconnect) when the buffer is full, rather than letting one slow reader stall everyone.

Not handling ping/pong. Idle connections can be closed by proxies or NAT timeouts. Set read deadlines and send periodic pings so dead connections are detected and removed.

Tips

Keep the hub pattern—one goroutine that owns the client map and selects on register, unregister, and broadcast channels—as your app grows. It scales cleanly and avoids most locking bugs.

Store messages in a slice with a cap (for example, the last 100) so new clients can receive recent history on connect. Without this, a user who joins late sees an empty room.

Use wss:// in production. Terminate TLS at a reverse proxy like Caddy or nginx and forward to your Go server; the Go code itself does not need to change.

Add a simple JSON envelope ({"user":"...","text":"..."}) early. Plain text messages become hard to extend once you add usernames or timestamps.

Troubleshooting

Connection refused or 404 on /ws. Confirm the route is registered before ListenAndServe and that the client URL matches the path exactly. Check the server is actually running on the port you expect.

Messages appear only in the sender's tab. The broadcast loop is probably not running—verify go handleMessages() is called before the server starts. Also confirm the sender is not writing directly to its own connection instead of sending to the broadcast channel.

Server panics with "concurrent map writes." Add a mutex around every read and write of the clients map, including the deferred delete.

Browser console shows a WebSocket handshake error. This is usually the origin check. During development, log the Origin header and compare it to what you expect; adjust CheckOrigin accordingly.

Connections drop after a minute of inactivity. Add ping messages on a ticker and set a read deadline slightly longer than the ping interval. This keeps intermediaries from timing out the connection.

Frequently Asked Questions

Do I need a database for a chat app?

No, not for a basic real-time chat. In-memory storage works for a single server. Add a database when you need persistence across restarts or multiple server instances.

Can I use the standard library only, without Gorilla?

Go's standard library has no WebSocket implementation. You can implement the protocol manually, but it is error-prone; Gorilla or nhooyr.io/websocket are the practical choices.

How do I scale to multiple servers?

Broadcast across instances using a message broker such as Redis Pub/Sub or NATS. Each server subscribes to the channel and forwards messages to its own connected clients.

Why does my client disconnect immediately?

Check the origin check first, then confirm the server is not closing the connection due to a read error. Enable logging around the upgrade and read loop to see which side closes first.

Is WebSocket the right choice over Server-Sent Events?

WebSocket is bidirectional, which suits chat. SSE is simpler but one-way, so sending messages would need a separate HTTP request. For chat, WebSocket is the better fit.