proto3忽略未知字段或扩展名处理

说明:

当遇到未知字段或扩展名时,默认解析将失败。
如果我们不希望失败而是忽略,可以设置allow_unknown_field_和allow_unknown_extension_。

举例:

场景:
程序使用 google::protobuf::TextFormat::Parse 解析配置。
如果配置有新加字段,而程序又没有重新编译pb文件,那么会解析失败。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
int ReadCfgData(const std::string& file, google::protobuf::Message* message)
{
using google::protobuf::io::FileInputStream;
int fd = open(file.c_str(), O_RDONLY);
if (fd < 0)
{
LogErr("can't open file.{}", file);
return -1;
}
FileInputStream input(fd);
input.SetCloseOnDelete(true);
if (file.substr(file.find_last_of(".")) == ".txt")
{
auto parse = google::protobuf::TextFormat::Parser();
parse.AllowUnknownField(true); // 此处设置allow_unknown_field_为true,将会忽略未知字段
if (!parse.Parse(&input, message))
{
LogErr("txt file.{} parse error", file);
return -2;
}
}
else
{
if (!message->ParseFromZeroCopyStream(&input))
{
LogErr("bytes file.{} parse error", file);
return -3;
}
}
return 0;
}

注意:

设置忽略后将生成警告消息,并且可能会隐藏一些错误。

proto3忽略未知字段或扩展名处理
https://www.inktea.eu.org/2024/1043.html
作者
inktea
发布于
2024年8月28日
许可协议