Can protobuf service method return primitive type?

15,116

Solution 1

No, you cannot use a primitive type as either the request or response. You must use a message type.

This is important because a message type can be extended later, in case you decide you want to add a new parameter or return some additional data.

Solution 2

If you want to return a primitive type, wrap it in a message and return it:

message Name {
  string name = 1;
}

In case you don't want to return anything, void I mean, you can just create an empty message:

message Void {} 

message Name {
  string name = 1;
}

..
service MyService{
  rpc MyFunc(Name) returns (Void);
}

Solution 3

You can return scalar datatypes like bool, int, etc by making use of wrappers.proto

service.proto file:

import "message.proto";
import "google/protobuf/wrappers.proto";

service Service {
    rpc request (Request) returns (.google.protobuf.BoolValue); 
}
Share:
15,116
4ntoine
Author by

4ntoine

Updated on June 05, 2022

Comments

  • 4ntoine
    4ntoine about 2 years

    I'm trying to use Google protobuf and i 'm having the next descriptions:

    message.proto file:

    message Request {
       required int32 id = 1;
       optional string value = 2;
    }
    

    service.proto file:

    import "message.proto";
    
    service Service {
        rpc request (Request) returns (bool);
    }
    

    I'm trying to generate c++ sources and getting an error:

    $ protoc service.proto --cpp_out=/tmp/proto/build

    service.proto:4:40: Expected message type.

    Do i have to return user-defined types only? Are primitive (like bool or string) supported? Can i use primitive types as service method argument (instead of Request in my example)?