DEV Community

Cover image for How to Build a Simple WebSocket Server in Go (Step-by-Step Guide)
David Jesse Odhiambo
David Jesse Odhiambo

Posted on • Edited on

How to Build a Simple WebSocket Server in Go (Step-by-Step Guide)

In the previous article HTTP vs WebSockets: What Every Beginner Needs to Know we learned about WebSockets and how they power real-time features like chat apps and live dashboards. But how do you actually build one with Go?

In this beginner-friendly guide, we’ll walk through how to:

✅ Set up a WebSocket server in Go
✅ Handle real-time messages
✅ Connect to it from a browser using JavaScript

This is Part 2 of the series. If you’re new to WebSockets, read Part 1: HTTP vs WebSockets—What Every Beginner Should Know first.


🔌 What is Gorilla WebSocket?

Gorilla WebSocket is a popular Go package that makes working with WebSockets easier.

  • ✅ Actively maintained
  • ✅ Full control over message handling
  • ✅ Works well with net/http

Setting up a WebSocket server in Go with Gorilla WebSocket

📦 Step 1: Install Gorilla WebSocket

While in your Go project's directory, open your terminal and run:

go get -u github.com/gorilla/websoc
Enter fullscreen mode Exit fullscreen mode

🛠️ Step 2: Build the WebSocket Server

Let’s write a basic WebSocket server in Go.

Create a file named main.go:

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
    // Allow all connections
    CheckOrigin: func(r *http.Request) bool { return true },
}

func handleWebSocket(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println("Upgrade error:", err)
        return
    }
    defer conn.Close()

    for {
        messageType, msg, err := conn.ReadMessage()
        if err != nil {
            log.Println("Read error:", err)
            break
        }

        log.Printf("Received: %s\n", msg)

        // Echo message back to client
        if err := conn.WriteMessage(messageType, msg); err != nil {
            log.Println("Write error:", err)
            break
        }
    }
}

func main() {
    http.HandleFunc("/ws", handleWebSocket)

    fmt.Println("Server started at http://localhost:8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}
Enter fullscreen mode Exit fullscreen mode

🌐 Step 3: Simple Frontend (HTML + JavaScript)

Create a file named index.html in the same folder:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>WebSocket Test</title>
</head>
<body>
  <h2>WebSocket Echo Client</h2>
  <input id="msgInput" type="text" placeholder="Type a message..." />
  <button onclick="sendMessage()">Send</button>
  <ul id="messages"></ul>

  <script>
    const ws = new WebSocket("ws://localhost:8080/ws");

    ws.onmessage = (event) => {
      const li = document.createElement("li");
      li.textContent = "Received: " + event.data;
      document.getElementById("messages").appendChild(li);
    };

    function sendMessage() {
      const input = document.getElementById("msgInput");
      ws.send(input.value);
      input.value = "";
    }
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

▶️ Step 4: Run Your Server

  1. Run the Go server:
go run main.go
Enter fullscreen mode Exit fullscreen mode
  1. Open index.html in your browser (just double-click it).

  2. Type a message and click Send — you should see your message echoed back in the browser!


🧪 How It Works

  • Your browser connects to /ws using WebSocket protocol.
  • Messages are sent to the server.
  • The server reads them and echoes them back.
  • All communication happens over a persistent connection.

🚀 Next Steps?

You’ve just built a real-time WebSocket server with Go! Now imagine what else you can do:

  • Build a chat app 🗨️
  • Add notifications 🔔
  • Stream sensor data 📈

In the next article, Real-Time Messaging with Go and JavaScript, we’ll take this further with broadcasting messages to multiple clients (like a real chat room).

✅ Follow me for more beginner-friendly Go tutorials!
Drop a comment if you have questions, or if you’ve built something cool with WebSockets!

Top comments (0)