Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a simple boolean value in ProtoBuffer?

in my proto file, I define a service interface:

syntax = "proto3";

package mynamespace;

import "google/protobuf/empty.proto";

service MyService {
    rpc isTokenValid (TokenRequest) returns (TokenResponse) {
    }
}

message TokenRequest {
    string token = 1;
}

message TokenResponse {
    bool valid = 1;
}

The above works well, however, I think the TokenResponse is ugly. the bool valid = 1 is redundant, ideally it should be like the following

rpc isTokenValid (TokenRequest) returns (BooleanResponse) {
}

But I didn't figure out how to write proto file like that, can any expert share some best practice on that?

Thanks in advance!

Updates:

How to return an array directly? For example, this is my code:

service MyService {
    rpc arrayResponse (TokenRequest) returns (ArrayResponse) {}
}

message ArrayResponse {
    repeated Data data = 1;
}

message Data {
    string field1 = 1;
    string field2 = 2;
}

I think this is ugly, how to refactor in the correct google way?

Thanks!

like image 254
Jeff Tian Avatar asked Dec 26 '18 09:12

Jeff Tian


People also ask

How do I set default value in Protobuf?

For bool s, the default value is false. For numeric types, the default value is zero. For enums , the default value is the first value listed in the enum's type definition. This means care must be taken when adding a value to the beginning of an enum value list.

What is the difference between proto2 and Proto3?

Proto3 is the latest version of Protocol Buffers and includes the following changes from proto2: Field presence, also known as hasField , is removed by default for primitive fields. An unset primitive field has a language-defined default value.

What does oneof mean in Protobuf?

Protocol Buffer (Protobuf) provides two simpler options for dealing with values that might be of more than one type. The Any type can represent any known Protobuf message type. And you can use the oneof keyword to specify that only one of a range of fields can be set in any message.

How do you comment in a proto file?

Adding Comments To add comments to your .proto files, use C/C++-style // and /* ... */ syntax.


1 Answers

Why not just use the predefined BoolValue as specified in Google's wrappers.proto for your response?

Something like:

syntax = "proto3";

package mynamespace;

import "google/protobuf/wrappers.proto";

service MyService {
    rpc isTokenValid (TokenRequest) returns (google.protobuf.BoolValue) {
    }
}

message TokenRequest {
    string token = 1;
}
like image 150
Michael Krause Avatar answered Sep 23 '22 04:09

Michael Krause