How do I use WebSockets for real-time updates?

WebSockets are a powerful tool for enabling real-time updates in web applications. They provide a full-duplex communication channel over a single TCP connection, which allows for instant data exchange between a client and server. This is particularly useful for applications like chat apps, live notifications, and collaborative tools.

Below is a basic example of how to set up a WebSocket server in Go and connect to it from a web client:

// Go WebSocket server setup package main import ( "fmt" "net/http" "github.com/gorilla/websocket" ) var upgrader = websocket.Upgrader{} func handler(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { fmt.Println("Error during connection upgrade:", err) return } defer conn.Close() for { msgType, msg, err := conn.ReadMessage() if err != nil { fmt.Println("Error reading message:", err) break } fmt.Println("Received:", string(msg)) if err := conn.WriteMessage(msgType, msg); err != nil { fmt.Println("Error writing message:", err) break } } } func main() { http.HandleFunc("/ws", handler) http.ListenAndServe(":8080", nil) }

WebSockets real-time updates Go language WebSocket server client-server communication live data