SoFunction
Updated on 2025-03-05

Golang uses melody to build a lightweight websocket service sample code

In Go, you can useginandmelodyLibrary to build a lightweight WebSocket service.ginis a popular web framework, andmelodyis a library for handling WebSockets. Here is a simple example code that demonstrates how to use itginandmelodyBuild WebSocket service:

package main
import (
	"fmt"
	"net/http"
	"/gin-gonic/gin"
	"/olahol/melody"
)
func main() {
	r := ()
	// Create Melody instance	m := ()
	// Register WebSocket handler function	("/ws", func(c *) {
		err := (, )
		if err != nil {
			(err)
		}
	})
	// Handle WebSocket connections	(func(s *) {
		("WebSocket connected")
	})
	// Process WebSocket messages	(func(s *, msg []byte) {
		("Received message:", string(msg))
		// Send messages to all connected clients		(msg)
	})
	// Handle WebSocket disconnection	(func(s *) {
		("WebSocket disconnected")
	})
	// Start HTTP server	("WebSocket server listening on :8080")
	(":8080", r)
}

In the example above, we first create aginofEngineInstance and created amelodyofMelodyExample.

Then, we useMethod will/wsThe path is registered as a WebSocket handler. In the processing function, we useMethod to handle WebSocket connections.

Next, we useMethods to handle WebSocket connection events, usingMethods to handle WebSocket message events, usingMethod handles WebSocket disconnection event.

existHandleMessageIn the method, we print the received message and useMethod broadcasts messages to all connected clients.

Finally, we useThe function starts the HTTP server and listens on8080on the port.

Sample code of melody official website

package main
import (
	"/gin-gonic/gin"
	"/olahol/melody"
	"net/http"
)
func main() {
	r := ()
	m := ()
	("/", func(c *) {
		(, , "")
	})
	("/ws", func(c *) {
		(, )
	})
	(func(s *, msg []byte) {
		(msg)
	})
	(":5000")
}

Please note that the above example is usedginandmelodyLibrary, you need to import these two libraries in your project, you can install it using the following command:

go get /gin-gonic/gin
go get /olahol/melody

The above is a simple example that you can adjust and expand according to your specific needs.

This is the article about quickly building a lightweight websocket service in golang using melody. For more related content on golang to build a websocket service, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!