-
Notifications
You must be signed in to change notification settings - Fork 0
/
proto.go
54 lines (49 loc) · 1.15 KB
/
proto.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
package util
import (
"fmt"
"github.com/gogo/protobuf/proto"
"github.com/gogo/protobuf/types"
"github.com/e-zhydzetski/ws-test/api"
)
func MarshalProtoMessage(msg proto.Message) ([]byte, error) {
body, err := types.MarshalAny(msg)
if err != nil {
return nil, err
}
return proto.Marshal(&api.Msg{
Body: body,
})
}
func UnmarshalProtoMessage(bytes []byte) (proto.Message, error) {
var msg api.Msg
err := proto.Unmarshal(bytes, &msg)
if err != nil {
return nil, err
}
if msg.GetBody() == nil {
return nil, nil
}
typeURL := msg.Body.GetTypeUrl()
switch typeURL {
case "type.googleapis.com/ClientID":
var body api.ClientID
if err := types.UnmarshalAny(msg.Body, &body); err != nil {
return nil, err
}
return &body, nil
case "type.googleapis.com/ServerPing":
var body api.ServerPing
if err := types.UnmarshalAny(msg.Body, &body); err != nil {
return nil, err
}
return &body, nil
case "type.googleapis.com/ClientPong":
var body api.ClientPong
if err := types.UnmarshalAny(msg.Body, &body); err != nil {
return nil, err
}
return &body, nil
default:
return nil, fmt.Errorf("unknown message type: %s", typeURL)
}
}