DEV Community

Discussion on: Generate and serialize protobuf message in Go

Collapse
 
hjcian profile image
Max Cian

Thanks for your sharing, I have some update for you to check out.

I found a version mismatching issue when I followed your tutorial.

My versions:
protoc-gen-go v1.23.0
protoc v3.13.0

The error message is showed when I use jsonpb.Marshaler{}.MarshalToString :

message ProtoMessage
cannot use message (type protoreflect.ProtoMessage) as type protoiface.MessageV1 in argument to marshaler.MarshalToString:
    protoreflect.ProtoMessage does not implement protoiface.MessageV1 (missing ProtoMessage method)go
multiple-value marshaler.MarshalToString() in single-value contextgo
Enter fullscreen mode Exit fullscreen mode

I checked the solution discussed on github.com/golang/protobuf/issues/... to replace the function of ProtobufToJSON to solved this version mismatching problem with the following change:

func ProtobufToJSON(message proto.Message) (string, error) {
    marshaler := protojson.MarshalOptions{
        Indent:          "  ",
        UseProtoNames:   true,
        EmitUnpopulated: true,
    }
    b, err := marshaler.Marshal(message)
    return string(b), err
}
Enter fullscreen mode Exit fullscreen mode