-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket.go
49 lines (37 loc) · 967 Bytes
/
websocket.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package goat
import (
"context"
"errors"
"github.com/avos-io/goat/gen/goatorepo"
"github.com/coder/websocket"
"google.golang.org/protobuf/proto"
)
var errNonBinaryWebsocketMessage = errors.New("invalid websocket message: not binary")
type goatOverWebsocket struct {
conn *websocket.Conn
}
func NewGoatOverWebsocket(ws *websocket.Conn) RpcReadWriter {
return &goatOverWebsocket{ws}
}
func (ws *goatOverWebsocket) Read(ctx context.Context) (*goatorepo.Rpc, error) {
typ, data, err := ws.conn.Read(ctx)
if err != nil {
return nil, err
}
if typ != websocket.MessageBinary {
return nil, errNonBinaryWebsocketMessage
}
var rpc goatorepo.Rpc
err = proto.Unmarshal(data, &rpc)
if err != nil {
return nil, err
}
return &rpc, nil
}
func (ws *goatOverWebsocket) Write(ctx context.Context, pkt *goatorepo.Rpc) error {
data, err := proto.Marshal(pkt)
if err != nil {
return err
}
return ws.conn.Write(ctx, websocket.MessageBinary, data)
}