WebSockets are a popular technology for enabling real-time communication between a client and a server. They provide a full-duplex, bidirectional communication channel that allows a client to receive updates from a server and send messages back to the server without having to constantly poll the server for updates.

Go is a popular programming language that is well-suited for building web applications, including those that make use of WebSockets. In this tutorial, we will cover the basics of working with WebSockets in Go programming.


Prerequisites

Before we dive into the code, there are a few prerequisites that you should be familiar with:

  • Basic knowledge of the Go programming language
  • Basic knowledge of HTML, CSS, and JavaScript
  • A text editor or IDE for writing Go code


Setting up the project

To get started, let's create a new Go project and add the necessary dependencies. We will be using the Gorilla WebSocket library, which provides a WebSocket implementation for Go.

To install the Gorilla WebSocket library, open a terminal and run the following command:

go get github.com/gorilla/websocket

Once the library is installed, create a new file called main.go and add the following code:

package main

import (
	"fmt"
	"net/http"

	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

func main() {
	http.HandleFunc("/", handleHome)
	http.HandleFunc("/ws", handleWebSocket)
	fmt.Println("Server started on :8080")
	http.ListenAndServe(":8080", nil)
}

func handleHome(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "index.html")
}

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

	for {
		messageType, message, err := conn.ReadMessage()
		if err != nil {
			fmt.Println("Read error:", err)
			return
		}

		fmt.Printf("Received message: %s\n", message)

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

This code sets up a basic HTTP server with two endpoints:

  1. The root endpoint ("/") serves a static HTML file called index.html.
  2. The "/ws" endpoint upgrades the HTTP connection to a WebSocket connection and handles incoming and outgoing messages.


Creating the client-side code

Now let's create the client-side code to connect to the WebSocket server and send and receive messages. Create a new file called index.html and add the following code:

<!DOCTYPE html>
<html>
	<head>
		<title>WebSockets in Go</title>
		<script>
			var socket = new WebSocket("ws://localhost:8080/ws");

			socket.onopen = function() {
				console.log("WebSocket connection established.");
				socket.send("Hello, server!");
			};

			socket.onmessage = function(event) {
				console.log("Received message: " + event.data);
			};

			socket.onclose = function(event) {
				console.log("WebSocket connection closed with code " + event.code);
			};
		</script>
	</head>
	<body>
		<h1>WebSockets in Go</h1>
	</body>
</html>

This code creates a new WebSocket connection to the server and sends a message as soon as the connection is established. It also listens for incoming messages and logs them to the console.


Testing the application

To test the application, run the following command in the terminal:

go run main.go

This will start the server on port 8080. Open a web browser and navigate to http://localhost:8080. You should see a blank page with the title "WebSockets in Go". Open the developer console in your browser and you should see the message "WebSocket connection established." logged to the console.

In the server console, you should see the message "Received message: Hello, server!" logged. The server then sends the same message back to the client, which should be logged to the console on the client side.


Conclusion

In this tutorial, we covered the basics of working with WebSockets in Go programming. We set up a basic HTTP server with an endpoint for upgrading the connection to a WebSocket connection, and we created client-side code to connect to the server and send and receive messages.

WebSockets provide a powerful tool for building real-time web applications, and Go is a great language for building high-performance web applications. With the Gorilla WebSocket library, it is easy to get started with WebSockets in Go and build powerful real-time applications.