@@ -22,7 +22,7 @@ import (
2222// and SetReadLimit.
2323//
2424// You must always read from the connection. Otherwise control
25- // frames will not be handled. See the docs on Reader.
25+ // frames will not be handled. See the docs on Reader and CloseRead .
2626//
2727// Please be sure to call Close on the connection when you
2828// are finished with it to release the associated resources.
@@ -319,10 +319,8 @@ func (c *Conn) handleControl(ctx context.Context, h header) error {
319319// to be closed so you do not need to write your own error message.
320320// This applies to the Read methods in the wsjson/wspb subpackages as well.
321321//
322- // You must read from the connection for close frames to be read.
323- // If you do not expect any data messages from the peer, just call
324- // Reader in a separate goroutine and close the connection with StatusPolicyViolation
325- // when it returns. See the writeOnly example.
322+ // You must read from the connection for control frames to be handled.
323+ // If you do not expect any data messages from the peer, call CloseRead.
326324//
327325// Only one Reader may be open at a time.
328326//
@@ -388,6 +386,21 @@ func (c *Conn) reader(ctx context.Context) (MessageType, io.Reader, error) {
388386 return MessageType (h .opcode ), r , nil
389387}
390388
389+ // CloseRead will close the connection if any data message is received from the peer.
390+ // Call this when you are done reading data messages from the connection but will still write
391+ // to it. Since CloseRead is still reading from the connection, it will respond to ping, pong
392+ // and close frames automatically. It will only close the connection on a data frame. The returned
393+ // context will be cancelled when the connection is closed.
394+ func (c * Conn ) CloseRead (ctx context.Context ) context.Context {
395+ ctx , cancel := context .WithCancel (ctx )
396+ go func () {
397+ defer cancel ()
398+ c .Reader (ctx )
399+ c .Close (StatusPolicyViolation , "unexpected data message" )
400+ }()
401+ return ctx
402+ }
403+
391404// messageReader enables reading a data frame from the WebSocket connection.
392405type messageReader struct {
393406 c * Conn
0 commit comments