SoFunction
Updated on 2025-03-04

Deep understanding of WebSocket and WSS support in Golang

introduction

WebSocket is a protocol for full-duplex communication on a single TCP connection, which provides a simple and powerful way to communicate in real time. WSS (WebSocket Secure) is a protocol that uses WebSocket through encryption, which can communicate on a secure transport layer. This article will explore the support of WebSocket and WSS in Golang, introduce how to build WebSocket servers and clients using Golang, and provide some practical examples.

WebSocket in Golang

Golang is a simple and efficient programming language that provides powerful concurrency performance and rich network programming support. In Golang, you can use the official onesnet/httpPackage and/gorilla/websocketPackage to implement the functions of WebSocket.

Build a WebSocket Server

To build a WebSocket server, you need to import it first/gorilla/websocketpackage and register a handler for handling WebSocket requests. Here is a simple example that demonstrates how to build a WebSocket server using Golang:

package main

import (
	"fmt"
	"log"
	"net/http"
	"/gorilla/websocket"
)

var upgrader = {
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

func WebSocketHandler(w , r *) {
	conn, err := (w, r, nil)
	if err != nil {
		("Failed to upgrade to WebSocket:", err)
		return
	}

	defer ()

	for {
		// Read the message sent by the client		_, message, err := ()
		if err != nil {
			("Failed to read message:", err)
			break
		}

		("Received message:", string(message))

		// Send a message to the client		err = (, []byte("Hello, client!"))
		if err != nil {
			("Failed to write message:", err)
			break
		}
	}
}

func main() {
	("/websocket", WebSocketHandler)
	("WebSocket server is running on :8080")
	(":8080", nil)
}

In the above code, we first import/gorilla/websocketpackage, and define aupgraderObject. Then, we implemented aWebSocketHandlerFunction to handle WebSocket requests. In this function we useMethod to upgrade HTTP connection to WebSocket connection and passMethod reads the message sent by the client and usesMethod sends a message to the client. Finally, we useThe function willWebSocketHandlerThe function is registered as a handler for handling WebSocket requests and usesThe function starts the WebSocket server.

Build a WebSocket Client

To build a WebSocket client, we can use/gorilla/websocketPackage providedDialFunction to establish a connection to the WebSocket server. Here is a simple example that demonstrates how to build a WebSocket client using Golang:

package main

import (
	"fmt"
	"log"
	"net/url"
	"/gorilla/websocket"
)

func main() {
	u := {Scheme: "ws", Host: "localhost:8080", Path: "/websocket"}
	conn, _, err := ((), nil)
	if err != nil {
		("Failed to connect to WebSocket server:", err)
		return
	}

	defer ()

	// Send a message to the server	err = (, []byte("Hello, server!"))
	if err != nil {
		("Failed to write message:", err)
		return
	}

	// Read the message sent by the server	_, message, err := ()
	if err != nil {
		("Failed to read message:", err)
		return
	}

	("Received message:", string(message))
}

In the above code, we first import/gorilla/websocketPackage and useMethod to establish a connection to the WebSocket server. Then, we useMethod sends a message to the server and usesMethod reads the message sent by the server. Finally, we print out the received message.

WSS in Golang

Generate a self-signed certificate

To use WSS in Golang, you first need to generate a self-signed certificate. You can use the OpenSSL tool to generate a self-signed certificate. Here is a simple example that demonstrates how to generate a self-signed certificate:

$ openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout  -out 

In the above command, we useopenssl reqThe command generates a self-signed certificate and saves the private key toIn the file, save the public key toin the file. In actual use, you may need to generate certificates according to your needs.

WebSocket Server and Client Using WSS

To use WSS in Golang, we only need to use TLS configuration in HTTP server and client. Here is a simple example that demonstrates how to build a WebSocket server and client using WSS in Golang:

package main

import (
	"fmt"
	"log"
	"net/http"
	"/gorilla/websocket"
)

var upgrader = {
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

func WebSocketHandler(w , r *) {
	conn, err := (w, r, nil)
	if err != nil {
		("Failed to upgrade to WebSocket:", err)
		return
	}

	defer ()

	for {
		_, message, err := ()
		if err != nil {
			("Failed to read message:", err)
			break
		}

		("Received message:", string(message))

		err = (, []byte("Hello, client!"))
		if err != nil {
			("Failed to write message:", err)
			break
		}
	}
}

func main() {
	("/websocket", WebSocketHandler)
	("WebSocket server is running on :8080")
	err := (":8080", "", "", nil)
	if err != nil {
		("Failed to start WebSocket server:", err)
	}
}

In the above code, we first import/gorilla/websocketpackage, and define aupgraderObject. Then, we implemented aWebSocketHandlerFunction to handle WebSocket requests. Finally, we useFunction starts a WebSocket server using WSS and provides certificate filesand private key file

For WebSocket clients, you only need to use it when establishing a connectionDialTLSMethod and provide the URL of the certificate. Here is a simple example:

package main

import (
	"fmt"
	"log"
	"net/url"
	"/gorilla/websocket"
)

func main() {
	u := {Scheme: "wss", Host: "localhost:8080", Path: "/websocket"}
	conn, _, err := ((), nil)
	if err != nil {
		("Failed to connect to WebSocket server:", err)
		return
	}

	defer ()

	err = (, []byte("Hello, server!"))
	if err != nil {
		("Failed to write message:", err)
		return
	}

	_, message, err := ()
	if err != nil {
		("Failed to read message:", err)
		return
	}

	("Received message:", string(message))
}

In the above code, we first import/gorilla/websocketPackage and useMethod to establish a WebSocket connection using WSS.

Security considerations

In the process of building WebSocket and WSS using Golang, ensuring data security is crucial. Here are a few security issues that should be considered when implementing WebSocket and WSS.

1. SSL/TLS encryption

The WSS protocol ensures the secure transmission of data by adding an SSL/TLS encryption layer on the basis of the HTTP protocol. In Golang, you can useFunction to start a WebSocket server using WSS, and implement encrypted transmission by providing certificates and private keys.

2. Cross-site scripting attack (XSS) protection

Cross-site scripting attack (XSS) is a common method of cyber attack where attackers steal sensitive information or engage in other malicious behavior by inserting malicious scripts into web pages. To protect WebSocket applications from XSS attacks, the following measures can be taken:

  • Input Verification and Filtering: Ensure that all data entered by users are verified and filtered to prevent injection of malicious scripts.
  • Safe content parsing: Use a secure way to parse and render user-provided content, such as using HTML escape to prevent injection attacks.

3. Cross-site request forgery (CSRF) protection

Cross-site request forgery (CSRF) is an attack method in which an attacker performs illegal operations by forging the request of a legitimate user. To prevent WebSocket applications from being attacked by CSRF, the following measures can be taken:

  • Add CSRF Token: Add CSRF token in each request and verify the validity of the token on the server side.
  • Restricting Connectable Domains and Sources: By restricting connected domains and sources on the server side, you can prevent malicious sites from establishing WebSocket connections.

To sum up, in order to ensure the security of WebSocket and WSS, in addition to using SSL/TLS encryption, protection against XSS and CSRF attacks should also be considered. By taking appropriate security measures and implementing best practices, we can improve the security of WebSocket and WSS applications.

Summarize

This article introduces the support of WebSocket and WSS in Golang. We first understand the basic concepts and features of WebSocket and WSS, and then demonstrate how to use Golang to build WebSocket servers and clients and implement the functionality of WSS using self-signed certificates. Through actual code examples, we demonstrate the powerful features and simplicity and ease of use of WebSocket and WSS in Golang.

This is the end of this article about a deep understanding of the support of WebSocket and WSS in Golang. For more related content on Golang, please search for my previous articles or continue browsing the related articles below. I hope you can support me more in the future!