Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining custom go struct tags for protobuf message fields

I am new to grpc and have been trying to just fetch a json response from a webserver. The stub can then request the json from the rpc server.

In my .proto file, I created a message type:

message Post {
    int64 number = 1;
    string now = 2;
    string name = 3;
}

But I am not able to marshal the number field, since protoc produces the struct pb.go file with a number tag:

{
        "no": "23",
        "now": "12:06:46",
        "name": "bob"
}

How can I force the Message to be 'converted' with a tag other than the lowercase name of the message field? Such as using the json tag no, even if the field name in the Message is number.

like image 649
ChaChaPoly Avatar asked Aug 13 '18 18:08

ChaChaPoly


1 Answers

You can set a proto3 field option on the proto message definition with a json_name

message Post {
    int64 number = 1 [json_name="no"];
    string now = 2;
    string name = 3;
}

link to the docs

like image 84
Zak Avatar answered Sep 19 '22 11:09

Zak