Skip to content

Commit

Permalink
Use net.ErrClosed
Browse files Browse the repository at this point in the history
Go 1.16 has introduced net.ErrClosed, which should be returned/wrapped when an
I/O call is performed on a network connection which has already been closed.
This is useful to avoid cluttering logs with messages like "failed to close
WebSocket: already wrote close".

Closes: coder#286
  • Loading branch information
emersion committed May 19, 2021
1 parent 8dee580 commit 537d8eb
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 7 deletions.
5 changes: 1 addition & 4 deletions close_notjs.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ package websocket
import (
"context"
"encoding/binary"
"errors"
"fmt"
"log"
"time"
Expand Down Expand Up @@ -48,15 +47,13 @@ func (c *Conn) closeHandshake(code StatusCode, reason string) (err error) {
return nil
}

var errAlreadyWroteClose = errors.New("already wrote close")

func (c *Conn) writeClose(code StatusCode, reason string) error {
c.closeMu.Lock()
wroteClose := c.wroteClose
c.wroteClose = true
c.closeMu.Unlock()
if wroteClose {
return errAlreadyWroteClose
return errClosed
}

ce := CloseError{
Expand Down
5 changes: 2 additions & 3 deletions write.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"context"
"crypto/rand"
"encoding/binary"
"errors"
"fmt"
"io"
"time"
Expand Down Expand Up @@ -53,14 +52,14 @@ type msgWriter struct {

func (mw *msgWriter) Write(p []byte) (int, error) {
if mw.closed {
return 0, errors.New("cannot use closed writer")
return 0, errClosed
}
return mw.mw.Write(p)
}

func (mw *msgWriter) Close() error {
if mw.closed {
return errors.New("cannot use closed writer")
return errClosed
}
mw.closed = true
return mw.mw.Close()
Expand Down

0 comments on commit 537d8eb

Please sign in to comment.