当前位置 : 主页 > 大数据 > 区块链 >

Protobuf3:使用正则表达式进行字符串验证

来源:互联网 收集:自由互联 发布时间:2021-06-22
我一直在使用 Protobuf3来定义PB消息: syntax = "proto3";package vioozer_protobuf;message Update{ string sensor_id = 1; ...} 在我的系统中,传感器具有唯一的id格式(a-la SENSOR-1342r43),可以使用正则表达式轻松验
我一直在使用 Protobuf3来定义PB消息:

syntax = "proto3";
package vioozer_protobuf;

message Update
{
  string sensor_id = 1;
  ...
}

在我的系统中,传感器具有唯一的id格式(a-la SENSOR-1342r43),可以使用正则表达式轻松验证.

有没有办法将一个正则表达式验证器添加到protobuf字段,以便只有符合正则表达式的字符串才会被接受到该字段中?

Protobuf不支持开箱即用的消息验证,但可以使用插件添加它(这是唯一的方法,但并不简单).

您可以尝试查找现有插件,也可以创建自己的插件(如果您的语言没有现有的插件).

如果您决定编写自己的插件,那么第一步是为字段定义a custom option:

package yourcompany;

import "google/protobuf/descriptor.proto";

extend google.protobuf.FieldOptions {
    optional string validator = 51234;
}

此选项允许您为具体字段指定正则表达式.然后,您应用新的自定义选项:

message Update {
    string sensor_id = 1 [(yourcompany.validator) = "SENSOR-???????"];
    // ...
}

其次,更具挑战性的步骤是write your own plugin,以便为生成的代码添加验证逻辑:

Additionally, plugins are able to insert code into the files generated by other code generators. See the comments about “insertion points” in 07002 for more on this. This could be used, for example, to write a plugin which generates RPC service code that is tailored for a particular RPC system. See the documentation for the generated code in each language to find out what insertion points they provide.

您的插件必须检查自定义选项的值,并为字段生成其他验证代码.

网友评论