Message Definition

Skip to first unread message


Dec 21, 2021, 5:20:13 PM12/21/21
to Protocol Buffers
I have many messages that can be sent between 2 processes.  All of these messages have a few things in common.  they all have common 'header' fields that identify what type of message it is, the length of the message, they all have varying length payloads, and they all have a correlation id.  The type of message is 'constant' per message.

I am looking to use proto3, and I'm not seeing any constant functionality - yet.

A couple questions.
1) is there a way to define that type constant per message?
eg - Message1 type=1234
      Message2 type=4444

2) is there a way to define the service method such that I only need to define one method that takes any of the messages that have been defined (similar to java's passing interface type on a method)?
eg - sendMessage(MyMessageInterface), but in actuality, it can be Message1, Message2, ...  

Theo Rose

Dec 22, 2021, 11:54:56 AM12/22/21
to Protocol Buffers
#1 for achieving "constants" the use of enums and default tag would give you what you want, but this is only permitted in proto2
example: //Enums default to their zero value. By not using 0, you ensure a message is always explicitly set.
enum MessageType {
MSG_TYPE_1 = 1;
MSG_TYPE_2 = 2;

message MessageOne {
optional MessageType msg_type = 1 [default=MSG_TYPE_1];
optional string name = 2;

message MessageTwo {
optional MessageType msg_type = 1 [default=MSG_TYPE_2];
optional string name = 2;
#2 - This can be done by using OneOf fields(Compatible with both proto2 and proto3). OneOf might also be able to eliminate your need for constants to check for your message types. Both proto2 and proto3 uses the `has<OneOf field name>` to check which OneOf is being used. example:
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloResponse) {}

// The request message containing MessageOne and MessageTwo.
message HelloRequest {
oneof request_message {
MessageOne msg1 = 1;
MessageTwo msg2 = 2;

// The response message containing the greetings
message HelloResponse {
optional string message = 1;
This will generate code for `HasMsg1` and `HasMsg2`.
Reply all
Reply to author
0 new messages