## 问题描述
使用 nhooyr.io/websocket 起了websocket 服务
前端使用 ws.send 发送消息
``` js
ws.onopen = function () {
// Web Socket 已连接上,使用 send() 方法发送数据
ws.send('msg');
};
```
websocket 服务会报错
## 报错内容
``` shell
2021/04/29 14:41:11 read from client error: failed to read JSON message: failed to unmarshal JSON: invalid character 'xxx' looking for beginning of value
```
## 解决办法
原因在于 nhooyr.io/websocket 的 wsjson.Read 只能接受 json 格式的字符串
源码
```go
// Read reads a JSON message from c into v.
// It will reuse buffers in between calls to avoid allocations.
func Read(ctx context.Context, c *websocket.Conn, v interface{}) error {
return read(ctx, c, v)
}
func read(ctx context.Context, c *websocket.Conn, v interface{}) (err error) {
defer errd.Wrap(&err, "failed to read JSON message")
_, r, err := c.Reader(ctx)
if err != nil {
return err
}
b := bpool.Get()
defer bpool.Put(b)
_, err = b.ReadFrom(r)
if err != nil {
return err
}
err = json.Unmarshal(b.Bytes(), v)
if err != nil {
c.Close(websocket.StatusInvalidFramePayloadData, "failed to unmarshal JSON")
return fmt.Errorf("failed to unmarshal JSON: %w", err)
}
return nil
}
```
前端改成json格式发送
```js
ws.onopen = function () {
let msg = JSON.stringify({ "content": "连接成功" });
ws.send(msg);
};
```
有疑问加站长微信联系(非本文作者)