github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/remote/proto_serializer.go (about) 1 package remote 2 3 import ( 4 "fmt" 5 6 "google.golang.org/protobuf/proto" 7 "google.golang.org/protobuf/reflect/protoreflect" 8 "google.golang.org/protobuf/reflect/protoregistry" 9 ) 10 11 type protoSerializer struct{} 12 13 func newProtoSerializer() *protoSerializer { 14 return &protoSerializer{} 15 } 16 17 func (p *protoSerializer) Serialize(msg interface{}) ([]byte, error) { 18 if message, ok := msg.(proto.Message); ok { 19 bytes, err := proto.Marshal(message) 20 if err != nil { 21 return nil, err 22 } 23 24 return bytes, nil 25 } 26 return nil, fmt.Errorf("msg must be proto.Message") 27 } 28 29 func (p *protoSerializer) Deserialize(typeName string, bytes []byte) (interface{}, error) { 30 n, _ := protoregistry.GlobalTypes.FindMessageByName(protoreflect.FullName(typeName)) 31 32 pm := n.New().Interface() 33 34 err := proto.Unmarshal(bytes, pm) 35 return pm, err 36 } 37 38 func (protoSerializer) GetTypeName(msg interface{}) (string, error) { 39 if message, ok := msg.(proto.Message); ok { 40 typeName := proto.MessageName(message) 41 42 return string(typeName), nil 43 } 44 return "", fmt.Errorf("msg must be proto.Message") 45 }