In Go, you can usegin
andmelody
Library to build a lightweight WebSocket service.gin
is a popular web framework, andmelody
is a library for handling WebSockets. Here is a simple example code that demonstrates how to use itgin
andmelody
Build 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 agin
ofEngine
Instance and created amelody
ofMelody
Example.
Then, we useMethod will
/ws
The 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, using
Methods to handle WebSocket message events, using
Method handles WebSocket disconnection event.
existHandleMessage
In 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 on
8080
on 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 usedgin
andmelody
Library, 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!