【问题标题】:How can I compare read(1.proto) = read(2.proto) in Go(assuming there's just one message definition)?我如何在 Go 中比较 read(1.proto) = read(2.proto)(假设只有一个消息定义)?
【发布时间】:2022-12-03 16:30:48
【问题描述】:

上下文:我正在尝试解析this issue。

换句话说,JSON 字符串有一个 NormalizeJsonString()(有关更多上下文,请参阅 this:

// Takes a value containing JSON string and passes it through
// the JSON parser to normalize it, returns either a parsing
// error or normalized JSON string.
func NormalizeJsonString(jsonString interface{}) (string, error) {

允许具有以下代码:

return structure.NormalizeJsonString(old) == structure.NormalizeJsonString(new)

但它不适用于原型文件的字符串(所有原型文件都保证只有一个消息定义)。例如,我可以看到:

            syntax = "proto3";
          - package bar.proto;
            
          + package bar.proto;
            option java_outer_classname = "FooProto";
            
            message Foo {
              ...
          -   int64 xyz = 3;
          +   int64  xyz = 3;

某些 Go SDK 中是否有 NormalizeProtoString 可用?我找到了MessageDifferencer,但它只在 C++ 中。我考虑的另一个选择是用一个空格替换所有新行/空格组,但这有点老套。

【问题讨论】:

    标签: go protocol-buffers


    【解决方案1】:

    要在 Go 中比较两个 proto 文件,您可以使用 protoc 命令行工具将文件编译成称为 Protocol Buffer wire 格式的二进制表示形式。然后您可以比较生成的二进制文件以确定它们是否相等。

    以下是如何执行此操作的示例:

    1. 如果您还没有安装协议,请在您的系统上安装。

    2. 使用以下命令将 proto 文件编译为 Protocol Buffer 有线格式:

      protoc --encode=<message_type> <input_file.proto> <output_file>
      

      其中 <message_type> 是原型文件中定义的消息类型的完全限定名称,<input_file.proto> 是输入原型文件的路径,<output_file> 是输出二进制文件的路径。

      使用 ioutil.ReadFile 函数将输出二进制文件的内容读取到字节片中。

      使用 bytes.Equal 函数比较两个字节片的内容。此函数返回一个布尔值,指示两个切片的内容是否相等。

      例如,假设您有以下名为 foo.proto 的原型文件:

      syntax = "proto3";
      package foo;
      
      message Bar {
        int64 xyz = 1;
      }
      

      您可以使用以下命令将此文件编译为 Protocol Buffer 有线格式:

      protoc --encode=foo.Bar foo.proto foo.bin
      

      这将创建一个名为 foo.bin 的二进制文件,其中包含 foo.Bar 消息的二进制表示。

      然后,您可以使用 ioutil.ReadFile 函数将此文件的内容读取到字节片中:

      data, err := ioutil.ReadFile("foo.bin")
      if err != nil {
        // Handle the error
      }
      

      然后,您可以使用 bytes.Equal 函数将此字节片的内容与从另一个二进制文件读取的另一个字节片的内容进行比较:

      otherData, err := ioutil.ReadFile("other.bin")
      if err != nil {
        // Handle the error
      }
      
      if bytes.Equal(data, otherData) {
        // The contents of the two binary files are equal
      } else {
        // The contents of the two binary files are not equal
      }
      

      这是在 Go 中比较 proto 文件的简单方法。请注意,正如您在问题中提到的那样,此方法仅适用于包含单个消息定义的原型文件。如果您的原型文件包含多个消息定义,您将需要使用不同的方法。

    【讨论】:

      猜你喜欢
      • 2021-11-20
      • 2020-03-15
      • 2023-03-19
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多