Protobuf 默认值

Protobuf default values

我有一个用于登录的注册表单。当我开始输入时,文本会立即发送到检查登录可用性的服务器。

答案必须是0或1,真或假,取决于我产生进一步的行动。 但是 0/false 是默认字段值,它们不会被发送,字段只是保持为空,字段根本不是(当且仅当字段不等于其默认值时,才会在线发送字段)。

我能用它做什么?我明确需要得到 0 或 1 的答案。当然,我使用的是字符串,但这是错误的。

.proto

message InputChecking {
    string login       = 1;
    int32  loginStatus = 2;
    string mail        = 3;
    int32  mailStatus  = 4;
}

message RegistrationRequest {
    ...
}

message WrapperMessage {
    oneof msg {
        InputChecking mes_inputChecking = 1;
        RegistrationRequest mes_registrationRequest = 2;
    }   
}

.cpp

WrapperMessage wm; // protobuf message, is filled with data from the server

const google::protobuf::FieldDescriptor* inputCheckingField = wm.GetDescriptor()->FindFieldByName("mes_inputChecking");

if (wm.GetReflection()->HasField(wm, inputCheckingField)) // if inputCheckingField is
{
    // It says that such a field is, when he receives a message from the server with loginStatus = 0, but there are no fields

    const google::protobuf::FieldDescriptor* loginStatusField = wm.mes_inputchecking().GetDescriptor()->FindFieldByName("loginStatus");

    if (wm.mes_inputchecking().GetReflection()->HasField(wm.mes_inputchecking(), loginStatusField))
    {
            // It is only called when the login is different from 0
            Log("Login status = " + wm.mes_inputchecking().loginstatus()); 
    }
}

阅读 this thread 后,我找到了一种处理 nullable/default 字段的方法,它可以使用 oneof 包装器。

message Foo {
  int x = 1;
  oneof v1 { 
     int32 value1 = 2; 
     bool  value2 = 3;
  }
}

另一种选择是使用枚举:

enum LoginStatus {
   LOGINSTATUS_INVALID = 0,
   LOGINSTATUS_NOT_AVAILABLE = 1,
   LOGINSTATUS_AVAILABLE = 2
}

这既使代码更具可读性,又允许单独处理第三种状态(响应中缺少字段)。