Go by Example: WebSockets
Implement real-time, bidirectional communication using WebSockets in Go. This example uses the robust `gorilla/websocket` library to create a simple echo server, demonstrating the upgrade process and message handling loop.
Code
package main
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func echo(w http.ResponseWriter, r *http.Request) {
conn, _ := upgrader.Upgrade(w, r, nil)
defer conn.Close()
for {
// Read message from browser
msgType, msg, err := conn.ReadMessage()
if err != nil {
return
}
// Print the message to the console
fmt.Printf("%s sent: %s\n", conn.RemoteAddr(), string(msg))
// Write message back to browser
if err = conn.WriteMessage(msgType, msg); err != nil {
return
}
}
}
func main() {
http.HandleFunc("/echo", echo)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
http.ListenAndServe(":8080", nil)
}Explanation
WebSockets enable real-time, bidirectional communication over a single TCP connection. While Go has a legacy websocket package in x/net, the community standard is github.com/gorilla/websocket due to its stability and feature completeness.
Implementing WebSockets involves an "Upgrade" process where a standard HTTP request is promoted to a WebSocket connection. Once upgraded, the connection persists, allowing you to read and write messages asynchronously.
Security Note: Always configure the CheckOrigin field in your Upgrader. By default, it blocks requests from different origins to prevent Cross-Site WebSocket Hijacking. In production, you should verify that the Origin header matches your trusted domains.

