| 152 | } |
| 153 | |
| 154 | func (c *Conn) read(ctx context.Context) (MessageType, []byte, error) { |
| 155 | select { |
| 156 | case <-ctx.Done(): |
| 157 | c.Close(StatusPolicyViolation, "read timed out") |
| 158 | return 0, nil, ctx.Err() |
| 159 | case <-c.readSignal: |
| 160 | case <-c.closed: |
| 161 | return 0, nil, net.ErrClosed |
| 162 | } |
| 163 | |
| 164 | c.readBufMu.Lock() |
| 165 | defer c.readBufMu.Unlock() |
| 166 | |
| 167 | me := c.readBuf[0] |
| 168 | // We copy the messages forward and decrease the size |
| 169 | // of the slice to avoid reallocating. |
| 170 | copy(c.readBuf, c.readBuf[1:]) |
| 171 | c.readBuf = c.readBuf[:len(c.readBuf)-1] |
| 172 | |
| 173 | if len(c.readBuf) > 0 { |
| 174 | // Next time we read, we'll grab the message. |
| 175 | select { |
| 176 | case c.readSignal <- struct{}{}: |
| 177 | default: |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | switch p := me.Data.(type) { |
| 182 | case string: |
| 183 | return MessageText, []byte(p), nil |
| 184 | case []byte: |
| 185 | return MessageBinary, p, nil |
| 186 | default: |
| 187 | panic("websocket: unexpected data type from wsjs OnMessage: " + reflect.TypeOf(me.Data).String()) |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | // Ping is mocked out for Wasm. |
| 192 | func (c *Conn) Ping(ctx context.Context) error { |