@@ -22,7 +22,7 @@ import (
22
22
// and SetReadLimit.
23
23
//
24
24
// 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 .
26
26
//
27
27
// Please be sure to call Close on the connection when you
28
28
// are finished with it to release the associated resources.
@@ -319,10 +319,8 @@ func (c *Conn) handleControl(ctx context.Context, h header) error {
319
319
// to be closed so you do not need to write your own error message.
320
320
// This applies to the Read methods in the wsjson/wspb subpackages as well.
321
321
//
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.
326
324
//
327
325
// Only one Reader may be open at a time.
328
326
//
@@ -388,6 +386,21 @@ func (c *Conn) reader(ctx context.Context) (MessageType, io.Reader, error) {
388
386
return MessageType (h .opcode ), r , nil
389
387
}
390
388
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
+
391
404
// messageReader enables reading a data frame from the WebSocket connection.
392
405
type messageReader struct {
393
406
c * Conn
0 commit comments