-
Notifications
You must be signed in to change notification settings - Fork 2
/
helpers.go
67 lines (51 loc) · 1.52 KB
/
helpers.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
package xconn
import (
"fmt"
"github.com/gobwas/ws/wsutil"
"github.com/xconnio/wampproto-go/messages"
"github.com/xconnio/wampproto-go/serializers"
)
func ClientSideWSReaderWriter(binary bool) (ReaderFunc, WriterFunc, error) {
if !binary {
return wsutil.ReadServerText, wsutil.WriteClientText, nil
}
return wsutil.ReadServerBinary, wsutil.WriteClientBinary, nil
}
func ServerSideWSReaderWriter(binary bool) (ReaderFunc, WriterFunc, error) {
if !binary {
return wsutil.ReadClientText, wsutil.WriteServerText, nil
}
return wsutil.ReadClientBinary, wsutil.WriteServerBinary, nil
}
func ReadMessage(peer Peer, serializer serializers.Serializer) (messages.Message, error) {
payload, err := peer.Read()
if err != nil {
return nil, err
}
msg, err := serializer.Deserialize(payload)
if err != nil {
return nil, err
}
return msg, nil
}
func ReadHello(peer Peer, serializer serializers.Serializer) (*messages.Hello, error) {
msg, err := ReadMessage(peer, serializer)
if err != nil {
return nil, err
}
if msg.Type() != messages.MessageTypeHello {
return nil, fmt.Errorf("first message must be HELLO, but was %d", msg.Type())
}
hello := msg.(*messages.Hello)
return hello, nil
}
func WriteMessage(peer Peer, message messages.Message, serializer serializers.Serializer) error {
payload, err := serializer.Serialize(message)
if err != nil {
return fmt.Errorf("failed to serialize message: %w", err)
}
if err = peer.Write(payload); err != nil {
return fmt.Errorf("failed to write message: %w", err)
}
return nil
}