Sling Academy
Home/Golang/Creating WebSocket Servers in Go

Creating WebSocket Servers in Go

Last updated: November 27, 2024

What is a WebSocket?

WebSocket is a protocol that allows for persistent, bidirectional communication between a client and server. Once a WebSocket connection is established, data can be sent back and forth in real time, making it perfect for applications that require continuous data exchange, like chat applications, gaming, or real-time updates.

Setting Up Go for WebSocket Development

To start creating a WebSocket server in Go, make sure you have Go installed. You can download it from the official site. Once Go is installed, you can setup your project and dependencies.

mkdir websocket-example
cd websocket-example

Installing the Gorilla WebSocket Package

The Gorilla WebSocket package is a popular library for managing WebSocket connections in Go. Install this package using the following:

go get -u github.com/gorilla/websocket

Creating a Basic WebSocket Server

Now, let’s create a simple WebSocket server using the Gorilla WebSocket package. First, create a new Go file:

touch main.go

Open main.go in your preferred editor and enter 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
	},
}

func handleConnections(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		fmt.Println("Error upgrading connection:", err)
		return
	}

defer conn.Close()

	for {
		messageType, p, err := conn.ReadMessage()
		if err != nil {
			fmt.Println("Error reading message:", err)
			return
		}
		fmt.Printf("Received message: %s\n", p)

		if err := conn.WriteMessage(messageType, p); err != nil {
			fmt.Println("Error writing message:", err)
			return
		}
	}
}

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

	port := "8080"
	fmt.Printf("Starting server on http://localhost:%s\n", port)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		fmt.Println("Error starting server:", err)
	}
}

Running Your WebSocket Server

To run your server, open a terminal, navigate to your project directory, and execute:

go run main.go

Your WebSocket server should now be running on http://localhost:8080.

Testing Your WebSocket Server

You can test your WebSocket server using a simple HTML client. Create a new file named index.html:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Test</title>
</head>
<body>
    <h1>WebSocket Client</h1>
    <textarea id="messages" cols="30" rows="10" disabled></textarea>
    <button onclick="connectWebSocket()">Connect</button>
    <input id="messageInput" type="text" placeholder="Enter your message"/>
    <button onclick="sendMessage()">Send</button>

    <script>
      const messages = document.getElementById('messages');
      const messageInput = document.getElementById('messageInput');
      let socket;

      function connectWebSocket() {
        socket = new WebSocket('ws://localhost:8080/ws');

        socket.onopen = function() {
          messages.value += 'Connected to WebSocket server\n';
        };

        socket.onmessage = function(event) {
          messages.value += 'Received: ' + event.data + '\n';
        };
      }

      function sendMessage() {
        const message = messageInput.value;
        socket.send(message);
        messages.value += 'Sent: ' + message + '\n';
        messageInput.value = '';
      }
    </script>
</body>
</html>

Open index.html in a browser and click Connect. You can now send messages to your WebSocket server and receive back what you send, demonstrating a simple echo server.

Next Article: Streaming Data with HTTP in Go

Previous Article: Securing HTTP Servers in Go with HTTPS and Certificates

Series: Networking and Server

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant