func handleWebSocketRequest(w http.ResponseWriter, r *http.Request) { conn, err := websocket.Upgrade(w, r, nil, 1024, 1024) if err != nil { log.Println("Error upgrading to WebSocket:", err) return } // Use the Conn here }
func handleWebSocketConnection(conn *websocket.Conn) { for { // Read message from client messageType, p, err := conn.ReadMessage() if err != nil { log.Println("Error reading from WebSocket:", err) break } // Process the message. We are just going to echo it back err = conn.WriteMessage(messageType, p) if err != nil { log.Println("Error writing to WebSocket:", err) break } } // Cleanup the connection when we are done conn.Close() }In this example, we handle a Conn by reading messages in a loop and writing them back to the client. We use conn.ReadMessage() to read data from the client, conn.WriteMessage() to write data to the client, and conn.Close() to clean up the connection when we are done. Overall, the go golang.org.x.net.websocket package supports the WebSocket protocol in a clean and easy-to-use way. Besides Conn, this package also provides many other useful types and functions, such as Dialer, Handler, and Codec.