Skip to content

Commit cdeb980

Browse files
committed
ws_js.go: Add CloseNow
1 parent 25a5ca4 commit cdeb980

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

doc.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
//
2929
// - Accept always errors out
3030
// - Conn.Ping is no-op
31+
// - Conn.CloseNow is Close(StatusGoingAway, "")
3132
// - HTTPClient, HTTPHeader and CompressionMode in DialOptions are no-op
3233
// - *http.Response from Dial is &http.Response{} with a 101 status code on success
3334
package websocket // import "nhooyr.io/websocket"

ws_js.go

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ func (c *Conn) read(ctx context.Context) (MessageType, []byte, error) {
151151
return 0, nil, ctx.Err()
152152
case <-c.readSignal:
153153
case <-c.closed:
154-
return 0, nil, c.closeErr
154+
return 0, nil, errClosed
155155
}
156156

157157
c.readBufMu.Lock()
@@ -205,7 +205,7 @@ func (c *Conn) Write(ctx context.Context, typ MessageType, p []byte) error {
205205

206206
func (c *Conn) write(ctx context.Context, typ MessageType, p []byte) error {
207207
if c.isClosed() {
208-
return c.closeErr
208+
return errClosed
209209
}
210210
switch typ {
211211
case MessageBinary:
@@ -229,19 +229,28 @@ func (c *Conn) Close(code StatusCode, reason string) error {
229229
return nil
230230
}
231231

232+
// CloseNow closes the WebSocket connection without attempting a close handshake.
233+
// Use When you do not want the overhead of the close handshake.
234+
//
235+
// note: No different from Close(StatusGoingAway, "") in WASM as there is no way to close
236+
// a WebSocket without the close handshake.
237+
func (c *Conn) CloseNow() error {
238+
return c.Close(StatusGoingAway, "")
239+
}
240+
232241
func (c *Conn) exportedClose(code StatusCode, reason string) error {
233242
c.closingMu.Lock()
234243
defer c.closingMu.Unlock()
235244

245+
if c.isClosed() {
246+
return errClosed
247+
}
248+
236249
ce := fmt.Errorf("sent close: %w", CloseError{
237250
Code: code,
238251
Reason: reason,
239252
})
240253

241-
if c.isClosed() {
242-
return fmt.Errorf("tried to close with %q but connection already closed: %w", ce, c.closeErr)
243-
}
244-
245254
c.setCloseErr(ce)
246255
err := c.ws.Close(int(code), reason)
247256
if err != nil {
@@ -312,7 +321,7 @@ func dial(ctx context.Context, url string, opts *DialOptions) (*Conn, *http.Resp
312321
StatusCode: http.StatusSwitchingProtocols,
313322
}, nil
314323
case <-c.closed:
315-
return nil, nil, c.closeErr
324+
return nil, nil, errClosed
316325
}
317326
}
318327

0 commit comments

Comments
 (0)