How to unmarshal protbuf data into custom struct in Golang

Viewed 57

I have a proxy service that translate protobuf into another struct. I can just write some manual code to do that, but that is inefficient and boilerplate. I can also transform the protobuf data to JSON, and deserlize the JSON data into the destination struct, but the speed is slow and it is CPU heavy.

The Unmarshaler interface is now deprecated, and Message interface have internal types which I cannot implement in my project.

Is there a way I can do this now?

1 Answers

Psuedo code: basically, if Go's reflection supports setting and getting of struct / class fields by some sort of field identifier, then you can do this. Something like this in C# works, so long as the field types in the two classes are the same (because in C#, I'm doing object = object, which ends up being OK if they're the same actual type).

SourceStructType sourceStruct;
DestStructType destStruct;

foreach (Field sourceField in sourceStruct.GetType().GetFields())
{
    Field destField = destStruct.GetType().FindFieldByName(sourceField.name);
    destStruct.SetFieldValue(destField) = sourceStruct.GetFieldValue(sourceField);
}

If the structs are more complex - i.e. they have structs within them, then you'll have to recurse down into them. It can get fiddly, but once written you'll never have to write it ever again!

Related