Handle normal closure

This commit is contained in:
Daniel 2024-10-20 22:10:54 -04:00
parent 343dc86591
commit 5a296cb940
2 changed files with 7 additions and 3 deletions

View file

@ -2,6 +2,7 @@ package main
import ( import (
"encoding/json" "encoding/json"
"errors"
"flag" "flag"
"log" "log"
"net/http" "net/http"
@ -90,8 +91,11 @@ func main() {
defer close(done) defer close(done)
for { for {
t, message, err := c.ReadMessage() t, message, err := c.ReadMessage()
closeErr := &websocket.CloseError{}
if err != nil { if err != nil {
log.Println("read:", err) if !(errors.As(err, &closeErr) && closeErr.Code == 1000) { // normal closure
log.Println("read:", err)
}
return return
} }
@ -127,7 +131,7 @@ func main() {
case <-done: case <-done:
return return
case <-interrupt: case <-interrupt:
log.Println("interrupt") log.Println()
// Cleanly close the connection by sending a close message and then // Cleanly close the connection by sending a close message and then
// waiting (with timeout) for the server to close the connection. // waiting (with timeout) for the server to close the connection.

View file

@ -110,7 +110,7 @@ func (conn *wsConn) readPump(ctx context.Context, reg Registry, c Client) {
for { for {
_, message, err := conn.ReadMessage() _, message, err := conn.ReadMessage()
if err != nil { if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure, websocket.CloseNormalClosure) {
log.Debug().Err(err).Str("conn", conn.RemoteAddr().String()).Msg("unexpected close") log.Debug().Err(err).Str("conn", conn.RemoteAddr().String()).Msg("unexpected close")
return return
} }