package main import ( "log" "net/http" "golang.org/x/net/websocket" ) func echoHandler(ws *websocket.Conn) { for { var msg string err := websocket.Message.Receive(ws, &msg) if err != nil { log.Fatal(err) } log.Printf("received: %s", msg) err = websocket.Message.Send(ws, msg) if err != nil { log.Fatal(err) } log.Printf("sent: %s", msg) } } func main() { http.Handle("/echo", websocket.Handler(echoHandler)) err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal(err) } }
package main import ( "log" "net/http" "golang.org/x/net/websocket" ) func authHandler(ws *websocket.Conn) { // verify authentication if !authorized(ws.Request()) { log.Printf("unauthorized connection from %s", ws.RemoteAddr()) ws.Close() return } // handle WebSocket requests for { // ... } } func main() { http.Handle("/auth", websocket.Handler(authHandler)) err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal(err) } }This example adds an authentication step to the WebSocket connection. The "authorized" function checks if the WebSocket request is authorized based on some criteria and returns true or false. If the connection is unauthorized, the WebSocket connection is closed. Overall, the "golang.org.x.net.websocket" package is a useful library for implementing WebSocket servers in Go. It provides functions to handle the low-level details of WebSocket connections, allowing developers to focus on the application logic.