Skip to content

Commit 6eda9c5

Browse files
committed
Docs for CloseRead
1 parent 559c169 commit 6eda9c5

File tree

2 files changed

+9
-10
lines changed

2 files changed

+9
-10
lines changed

example_test.go

+1-5
Original file line numberDiff line numberDiff line change
@@ -74,11 +74,7 @@ func Example_writeOnly() {
7474
ctx, cancel := context.WithTimeout(r.Context(), time.Minute*10)
7575
defer cancel()
7676

77-
go func() {
78-
defer cancel()
79-
c.Reader(ctx)
80-
c.Close(websocket.StatusPolicyViolation, "server doesn't accept data messages")
81-
}()
77+
ctx = c.CloseRead(ctx)
8278

8379
t := time.NewTicker(time.Second * 30)
8480
defer t.Stop()

websocket.go

+8-5
Original file line numberDiff line numberDiff line change
@@ -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,11 @@ 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.
391394
func (c *Conn) CloseRead(ctx context.Context) context.Context {
392395
ctx, cancel := context.WithCancel(ctx)
393396
go func() {

0 commit comments

Comments
 (0)