Go websocket error: close 1006 (abnormal closure): unexpected EOF

Viewed 14665

I'm trying to write a simple go websocket server with gorilla/websocket

http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
    if os.Getenv("env") == "development" {
        upgrader.CheckOrigin = func(r *http.Request) bool { return true }
    }

    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Printf("Websocket error: %s", err)
        return
    }

    defer conn.Close()

    // Register client
    clients[conn] = true

    for {
        message := message.Message{}
        _, msg, err := conn.ReadMessage()
        if err != nil {
            log.Printf("Websocket error: %s", err)
            return
        }

        res, _ = json.Marshal(context.Game)

        // Send to every client that is currently connected
        for client := range clients {
            err := client.WriteMessage(websocket.TextMessage, res)
            if err != nil {
                // Remove connection
                client.Close()
                delete(clients, client)
            }
        }
    }
})

the _, msg, err := conn.ReadMessage() line is throwing an error and closing the websocket, but I'm not sure why.

The error is close 1006 (abnormal closure): unexpected EOF. How can I prevent this?

1 Answers

The error indicates that the peer closed the connection without sending a close message. The RFC calls this "abnormal closure", but the error is normal to receive.

Use IsUnexpectedCloseError to filter out expected close errors. The Gorilla Chat Example shows how use the function (view code here).

The application in the question has a data race on clients as pointed out by Adrian. The Gorilla Chat Example shows how to maintain a map of clients without a data race (hub).

Related