SoFunction
Updated on 2025-03-05

Project Practice of Golang to Implement WebSocket Service

We are exposed to various applications every day, such as social, online documents, live broadcasts, etc., and the backend needs to use WebSocket technology to provide real-time communication capabilities. This article introduces how to use Golang to implement real-time backend WebSocket service. First, use the Gin framework to build an http service, and then use the gorilla/websocket library to implement a simple backend WebSocket service. The example implements the process from 0 to 1, which is suitable for beginners to get started quickly.

Gin implements web applications

Create a Go project, add a new file, and write the following code:

package main
import "fmt"
func main() {
     ("Hello, World!")
}

Run it to see the output result. The following adds Web service functions. Install Gin library dependencies:

go get -u /gin-gonic/gin

Modify the contents of the above file:

package main
import (
  "fmt"
  "/gin-gonic/gin"
)
func main() {
    ("Hello, World!")
    // Create a Gin engine instance    r := ()
    // Add routing ping, simply return pong    ("/ping", func(c *) {
        (200, {
            "message": "pong",
        })
    })
    // listen and serve on 0.0.0.0:8080
    // Start HTTP service    () 
}

Run the program, access address: http://localhost:8080/ping, return the result:

{
"message": "pong"
}

Implement WebSocket Service

The main method of creating and modifying the file is hello(). There cannot be two main methods under the same package. The corresponding library needs to be installed: go get -u /gorilla/websocket, add the following content:

package main
import (
  "fmt"
  "log"
  "net/http"
  "/gin-gonic/gin"
  "/gorilla/websocket"
)
var upgrader = {
  // Solve cross-domain problems  CheckOrigin: func(r *) bool {
    return true
  },
} 
func ws(c *) {
  //Update get request using WebSocket protocol  ws, err := (, , nil)
  if err != nil {
   log. Print("upgrade:", err)
   return
  }
  defer ()
  // Listen to ws messages  for {
   // Read data from ws   mt, message, err := ()
   if err != nil {
    ("read:", err)
    break
   }
   ("recv: %s", message)
   //Write data to ws   err = (mt, message)
   if err != nil {
    ("write:", err)
    break
   }
  }
}
func main() {
    ("Websocket Server!")
    r := ()
    ("/ws", ws)
    ("localhost:8448")
}

The core logic is: after receiving the message, write the same content back to the client. The code adds comments, the main difference is the read and write messages in the for loop. The following is the html file to interact and create a new file:

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Univer Server</title>
</head>
<body>
     <script>
         var ws = new WebSocket("ws://localhost:8448/ws");
         // Triggered when opening the connection          = function(evt) {
             ("Connection open...");
             ("Hello WebSockets!");
         };
         //Triggered when a message is received          = function(evt) {
             ("Received Message: " + );
         };
         // Triggered when the connection is closed          = function(evt) {
             ("Connection closed.");
         };
     </script>
     Hello WebSocket.
</body>
</html>

There are three callback functions defined in the script tag. After connecting to WS, send a message to the server. When the server receives the message, it returns the same content, and triggers when the connection is closed at the end.

Start the test

First, start ws, go run, and wait for the client to connect after starting the server. Start the client below. We can use vs code live server to start accessing static pages, or use python to start http service. Open the command line interface in the project directory, enter the following command, and enable the http service:

python -m  9000

Access http://localhost:9000/ through the browser, open the browser console and you can see the information:

Connection open...
:21 Received Message: Hello WebSockets!
:25 Connection closed.

First, you see the first line (the log that was successfully printed in the connection), and then the message sent by the receiving server. Finally, close the server program and the client prints the connection disconnect log.

This is the end of this article about Golang's project practice of implementing WebSocket services. For more information about Golang WebSocket services, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!