Reputation: 1027
Normally, to convert a protobuf message from wire format to JSON, you simply unmarshal the wire format into a proto.Message
whose dynamic type is a concrete Go type (generated by protoc-gen-go), and then unmarshal that to JSON with the protojson
package.
I would like to know how to do the same if you don't have a concrete Go type, but a protoreflect.MessageDescriptor
instead. The descriptor should have all the information necessary to parse the wire format and construct a JSON (or other formats) from it, but I can't seem to find an API for that. It seems like I need something like the following:
func UnmarshalFromWire(b []byte, desc protoreflect.MessageDescriptor) (protoreflect.Message, error)
func MarshalToJSON(m protoreflect.Message) ([]byte, error)
Is there an API like that or similar?
Upvotes: 0
Views: 3192
Reputation: 1400
The dynamicpb
module does the first part (from MessageDescriptor
to proto.Message
, not protoreflect.Message
).
func UnmarshalFromWire(b []byte, desc protoreflect.MessageDescriptor) (proto.Message, error) {
m := dynamicpb.NewMessage(desc)
if err := proto.Unmarshal(b, m); err != nil {
return nil, err
}
return m, nil
}
The second part is just your standard protojson.Marshal
- since you now have a perfectly valid proto.Message
.
Upvotes: 2