Implement a WebSocket echo server using wsutil
masterFor a high-level implementation, use the wsutil package to handle message reading and writing. This approach abstracts the protocol internals while providing a simple interface for common tasks like reading client data and writing server messages.
Use ws.UpgradeHTTP to upgrade an incoming http.Request and wsutil.ReadClientData / wsutil.WriteServerMessage for the I/O loop.
package main
import (
"net/http"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
)
func main() {
http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, _, _, err := ws.UpgradeHTTP(r, w)
if err != nil {
// handle error
}
go func() {
defer conn.Close()
for {
msg, op, err := wsutil.ReadClientData(conn)
if err != nil {
// handle error
}
err = wsutil.WriteServerMessage(conn, op, msg)
if err != nil {
// handle error
}
}
}()
}))
})