How do I upgrade HTTP to WebSocket connections in Go?

In Go, upgrading an HTTP connection to a WebSocket connection can be done using the `golang.org/x/net/websocket` package or the popular `github.com/gorilla/websocket` package. This allows real-time, two-way communication between the server and the client. Below is an example of how to upgrade an HTTP connection to a WebSocket connection using the Gorilla WebSocket package.

package main import ( "net/http" "github.com/gorilla/websocket" "log" ) var upgrader = websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true }, } func handleWebSocket(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println(err) return } defer conn.Close() for { messageType, msg, err := conn.ReadMessage() if err != nil { log.Println(err) break } log.Printf("Received: %s", msg) if err := conn.WriteMessage(messageType, msg); err != nil { log.Println(err) break } } } func main() { http.HandleFunc("/ws", handleWebSocket) log.Println("Server started on :8080") if err := http.ListenAndServe(":8080", nil); err != nil { log.Fatal("ListenAndServe:", err) } }

Go WebSocket HTTP upgrade real-time communication Gorilla WebSocket