Creating a WebSocket server using Go can simplify the development process with existing libraries.gorilla/websocket
It is a very popular and powerful library for WebSocket applications in Go language. Here is a detailed step guide on how to use itgorilla/websocket
Create a WebSocket server and realize real-time broadcast of product information.
Installation dependencies
First, you need to install itgorilla/websocket
library. It can be installed through the following command:
go get /gorilla/websocket
Create a WebSocket Server
Next, we will create a simple WebSocket server that can receive client connections and broadcast product information to all connected clients.
1. Import the necessary packages
package main import ( "fmt" "log" "net/http" "time" "/gorilla/websocket" )
2. Set up the WebSocket upgrader
WebSocket connections need to be established through HTTP handshake.gorilla/websocket
Provides aUpgrader
Structure to handle this process.
var upgrader = { ReadBufferSize: 1024, WriteBufferSize: 1024, // Allow cross-domain access CheckOrigin: func(r *) bool { return true }, }
3. Create a WebSocket Processor
Define a function to handle WebSocket connections. In this function, we will read the message and broadcast the product information.
func serveWs(w , r *) { // Upgrade HTTP connection to WebSocket connection conn, err := (w, r, nil) if err != nil { ("Failed to set websocket upgrade:", err) return } defer () // Simulate product addition events for { item := map[string]interface{}{ "id": 1, "name": "Apple", "price": 2.5, } // Send product information to the client err := (item) if err != nil { ("Error writing message:", err) break } // Send every 5 seconds (5 * ) } }
4. Register the route and start the HTTP server
Finally, we need to register the route and start the HTTP server.
func main() { ("/ws", serveWs) ("Starting server on :8080") if err := (":8080", nil); err != nil { ("ListenAndServe: ", err) } }
Complete code
Combine the above code snippets together to get the complete WebSocket server code:
package main import ( "fmt" "log" "net/http" "time" "/gorilla/websocket" ) var upgrader = { ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: func(r *) bool { return true }, } func serveWs(w , r *) { conn, err := (w, r, nil) if err != nil { ("Failed to set websocket upgrade:", err) return } defer () for { item := map[string]interface{}{ "id": 1, "name": "Apple", "price": 2.5, } err := (item) if err != nil { ("Error writing message:", err) break } (5 * ) } } func main() { ("/ws", serveWs) ("Starting server on :8080") if err := (":8080", nil); err != nil { ("ListenAndServe: ", err) } }
Run the server
Save the file and run:
go run
Test connection
You can use any WebSocket client tool (such as browser developer tools) to test the connection. Connect tows://localhost:8080/ws
, you should receive product information every 5 seconds.
Extended features
- Multi-client support: A connection list can be maintained on the server side to broadcast messages to all connected clients.
- Message Type: Different message types can be defined so that the client can handle the corresponding process accordingly according to the message type.
- Error handling: Add more detailed error handling and logging for better debugging and monitoring.
This is the end of this article about using go to create a WebSocket server. For more related go WebSocket server content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!