0

In my test.proto file I have as below, i.e. no field inside message HTML, how do I set a value for the _html field of message Page?

message HTML{
    enum Type {
        NO_TYPE = 0;
        HTML5 = 1;
        XHTML = 2;
    }
}

message Page{ 
 optional HTML _html = 1;
}

How can I set the values?

echo _html : **???** | protoc --encode=Page test.proto  > binary.data

https://medium.com/@at_ishikawa/cli-to-generate-protocol-buffers-c2cfdf633dce

jps
  • 20,041
  • 15
  • 75
  • 79
  • you didn't respond yet to my last comment and updates of the answer. Did you meanwhile understand, that this can't work? Kindly consider upvoting and accepting the answer by clicking on the checkmark left of it. – jps Sep 22 '20 at 11:06

1 Answers1

0

How can I set the values?

you can't when it is defined like you have shown. The message HTML only contains a definition of an enum but no actual fields. You can either add a field in the message HTML, or define the type in Page as HTML.Type instead of just HTML:

test.proto:

message HTML{
    enum Type {
        NO_TYPE = 0;
        HTML5 = 1;
        XHTML = 2;
    }
}

message Page{ 
 optional HTML.Type _html = 1;
}

and then create a file test.txt:

_html: HTML5

you can create a binary file like this:

protoc --experimental_allow_proto3_optional --encode Page test.proto < test.txt > binary.data

and decode it :

protoc --experimental_allow_proto3_optional --decode Page test.proto < binary.data

The last command prints:

_html: HTML5

Apart from the enum definition, the HTML message is an Empty message, which even exists as a predefined message:

// A generic empty message that you can re-use to avoid defining duplicated
// empty messages in your APIs. A typical example is to use it as the request
// or the response type of an API method.
// The JSON representation for Empty is empty JSON object {}.
message Empty {}

jps
  • 20,041
  • 15
  • 75
  • 79
  • This is just an example to explain the issue, I cannot make any edits to the existing proto file thats the issue, is there any workaround without editing proto file? – Sanil Talauliker Sep 18 '20 at 06:31
  • No, it shows how you would normally solve the issue. Another - better - option is to add a field in the HTML message. The precondition, that the .proto file is - for whatever reason - unchangeable, hasn't been mentioned before. In this example `HTML _html` is a nested message with no fields but only a definition of an enum. My example shows how to use this enum. Now imagine you have two enums defined in the HTML message... Maybe I'm totally off here, but afaik this doesn't make much sense and can't be solved without changing the proto file. – jps Sep 18 '20 at 07:37