-
Notifications
You must be signed in to change notification settings - Fork 906
/
wsproto.go
80 lines (62 loc) · 1.38 KB
/
wsproto.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package migration
import (
"fmt"
"io"
"github.com/gorilla/websocket"
"google.golang.org/protobuf/proto"
"github.com/canonical/lxd/shared"
)
// ProtoRecv gets a protobuf message from a websocket.
func ProtoRecv(ws *websocket.Conn, msg proto.Message) error {
if ws == nil {
return fmt.Errorf("Empty websocket connection")
}
mt, r, err := ws.NextReader()
if err != nil {
return err
}
if mt != websocket.BinaryMessage {
return fmt.Errorf("Only binary messages allowed")
}
buf, err := io.ReadAll(r)
if err != nil {
return err
}
err = proto.Unmarshal(buf, msg)
if err != nil {
return err
}
return nil
}
// ProtoSend sends a protobuf message over a websocket.
func ProtoSend(ws *websocket.Conn, msg proto.Message) error {
if ws == nil {
return fmt.Errorf("Empty websocket connection")
}
w, err := ws.NextWriter(websocket.BinaryMessage)
if err != nil {
return err
}
defer func() { _ = w.Close() }()
data, err := proto.Marshal(msg)
if err != nil {
return err
}
err = shared.WriteAll(w, data)
if err != nil {
return err
}
return w.Close()
}
// ProtoSendControl sends a migration control message over a websocket.
func ProtoSendControl(ws *websocket.Conn, err error) {
message := ""
if err != nil {
message = err.Error()
}
msg := MigrationControl{
Success: proto.Bool(err == nil),
Message: proto.String(message),
}
_ = ProtoSend(ws, &msg)
}