Skip to content

Commit

Permalink
Panic if trying to close or start and already closed socket
Browse files Browse the repository at this point in the history
  • Loading branch information
rowanseymour committed Jan 15, 2024
1 parent 77c21ac commit 6daeb9a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
8 changes: 8 additions & 0 deletions httpx/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ func (s *socket) OnMessage(fn func([]byte)) { s.onMessage = fn }
func (s *socket) OnClose(fn func(int)) { s.onClose = fn }

func (s *socket) Start() {
if s.closingWithCode != 0 {
panic("can't start socket which is closed or closing")
}

s.conn.SetReadDeadline(time.Now().Add(maxReadWait))
s.conn.SetPongHandler(s.pong)

Expand All @@ -116,6 +120,10 @@ func (s *socket) Send(msg []byte) {
}

func (s *socket) Close(code int) {
if s.closingWithCode != 0 {
panic("can't close socket which is already closed or closing")
}

s.closingWithCode = code

s.outbox <- message{type_: websocket.CloseMessage, data: websocket.FormatCloseMessage(code, "")}
Expand Down
11 changes: 11 additions & 0 deletions httpx/websocket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,17 @@ func TestSocketMessages(t *testing.T) {

assert.Equal(t, 1001, serverCloseCode)
assert.Equal(t, 1001, connCloseCode)

// check we can no longer send to the socket or close it again, or restart it
assert.Panics(t, func() {
sock.Send([]byte("x"))
})
assert.Panics(t, func() {
sock.Close(1000)
})
assert.Panics(t, func() {
sock.Start()
})
}

func TestSocketClientCloseWithMessage(t *testing.T) {
Expand Down

0 comments on commit 6daeb9a

Please sign in to comment.