improve error handling in handleWsConn

This commit is contained in:
Łukasz Magiera 2019-07-13 14:44:20 +02:00
parent df90b72500
commit 96ed4225fb

View File

@ -25,20 +25,18 @@ type frame struct {
func handleWsConn(ctx context.Context, conn *websocket.Conn, handler handlers, requests <-chan clientRequest, stop <-chan struct{}) { func handleWsConn(ctx context.Context, conn *websocket.Conn, handler handlers, requests <-chan clientRequest, stop <-chan struct{}) {
incoming := make(chan io.Reader) incoming := make(chan io.Reader)
var incErr error
nextMessage := func() { nextMessage := func() {
mtype, r, err := conn.NextReader() mtype, r, err := conn.NextReader()
if err != nil { if err != nil {
r, _ := io.Pipe() incErr = err
r.CloseWithError(err) // nolint close(incoming)
incoming <- r
return return
} }
if mtype != websocket.BinaryMessage && mtype != websocket.TextMessage { if mtype != websocket.BinaryMessage && mtype != websocket.TextMessage {
r, _ := io.Pipe() incErr = errors.New("unsupported message type")
r.CloseWithError(errors.New("unsupported message type")) // nolint close(incoming)
incoming <- r
return return
} }
incoming <- r incoming <- r
@ -50,7 +48,14 @@ func handleWsConn(ctx context.Context, conn *websocket.Conn, handler handlers, r
for { for {
select { select {
case r := <-incoming: case r, ok := <-incoming:
if !ok {
if incErr != nil {
log.Debugf("websocket error", "error", incErr)
}
return // remote closed
}
var frame frame var frame frame
if err := json.NewDecoder(r).Decode(&frame); err != nil { if err := json.NewDecoder(r).Decode(&frame); err != nil {
log.Error("handle me:", err) log.Error("handle me:", err)
@ -107,6 +112,9 @@ func handleWsConn(ctx context.Context, conn *websocket.Conn, handler handlers, r
return return
} }
case <-stop: case <-stop:
if err := conn.Close(); err != nil {
log.Debugf("websocket close error", "error", err)
}
return return
} }
} }