'Generate Enums with a Display Name type attribute using protobuf
Been trying to consolidate our enums in our C# and Go libraries via protobuf and am currently stuck trying to figure out how to retain the 'Display Name' attribute of the enum. eg: Enum SpouseEx would have a display name of 'spouse ex'. The normal way we do this in C# is to define it in an attribute and in Go, we'd override the String() method. But not sure how to go about it using Protobuf.
I looked online and it seems I might need to use options/ custom https://developers.google.com/protocol-buffers/docs/proto3#customoptions and this is what I ended up using
syntax = "proto3";
import "google/protobuf/descriptor.proto";
package enums.test;
option go_package = "github.com/tester/common/proto/enums;enums";
extend google.protobuf.EnumValueOptions {
string enum_value_option = 5000;
}
enum TestEnum {
NA = 0;
ThisIsATest = 1 [(enum_value_option) = "this is a test"];
}
But the generated output doesn't give any indication that "this is a test" got compiled. Indeed, while testing the enum's string() function, I'm still just getting "ThisIsATest". Please note that the syntax for options is slightly different in proto3 than that of proto2.
Solution 1:[1]
Figured it out after going through this SO post How to access proto.EnumValueOptions extension values
Did not know about the GetExtension method but basically after looking at that answer, this is what I came up with:
func TestThis(t *testing.T) {
vals := enums.TestEnum_ThisIsATest.Descriptor().Values()
valDesc := vals.ByName("ThisIsATest")
ext := proto.GetExtension(valDesc.Options(), enums.E_TestValueOption)
fmt.Println(ext)
}
Now I just need to figure out how to abstract this out (if it's even possible) so I can reuse it during serialization/deserialization
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Newbie |
