I use https://pkg.go.dev/golang.org/x/net/websocket for creating a server-side websocket. All communication through it is in JSON. Thus, my code contains:
func wsHandler(ws *websocket.Conn) {
var evnt event
websocket.JSON.Receive(ws, &evnt)
…
However, this blocks until the connection is closed by the client. I know that this websocket package pre-dates context (and I know that there are newer websocket packages), still – is there really no way to wait for incoming frames in a non-blocking way?
this blocks until the connection is closed by the client.
The easiest way to handle concurrent blocking operations is to give them a goroutine. Goroutines, unlike processes or threads, are essentially "free".
func wsHandler(ws *websocket.Conn) {
go func() {
var evnt event
websocket.JSON.Receive(ws, &evnt)
....
}()
}