-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
envelope.go
50 lines (44 loc) · 1.09 KB
/
envelope.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
package persistencepg
import (
"encoding/json"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
)
// struct
type envelope struct {
ID string
Message json.RawMessage
EventIndex int
ActorName string
EventName string
}
type messageEnvelope struct {
Type string `json:"type"`
Payload json.RawMessage `json:"payload"`
}
func newEnvelope(message proto.Message) ([]byte, error) {
typeName := proto.MessageName(message)
bytes, err := json.Marshal(message)
if err != nil {
return nil, err
}
return json.Marshal(&messageEnvelope{Payload: bytes, Type: string(typeName)})
}
func (envelope *envelope) message() (proto.Message, error) {
me := &messageEnvelope{}
err := json.Unmarshal(envelope.Message, me)
if err != nil {
return nil, err
}
mt, err := protoregistry.GlobalTypes.FindMessageByName(protoreflect.FullName(me.Type))
if err != nil {
return nil, err
}
pm := mt.New().Interface()
err = json.Unmarshal(me.Payload, pm)
if err != nil {
return nil, err
}
return pm, nil
}