簡體   English   中英

使用 oneOf protobuf 字段將 yaml 解組到 proto3

[英]unmarshal yaml to proto3 with oneOf protobuf field

我有一個結構如下的原始消息:

syntax = "proto3";

message Bar {
  int64 id = 1;
  string name = 2;
  int64 value = 3;
}

message Msg {
  int32 baz = 1;
  oneof some_union {
     string foo = 2;
     Bar bar = 3;
  }
}

我可以想到兩種方法來編寫等效於消息的 yaml。 在第一種方法中,請參見下面的示例,它分配"some_union": null並且在“foo”字段中未設置任何值。

baz: 0
foo: "some_string"

在第二種方法中,請參見下面的示例,它會拋出一個錯誤,指出cannot unmarshal object into Go struct field

baz: 0
some_union:
  foo: "some_string"

我正在使用github.com/ghodss/yaml package 將 yaml 解組為原始消息。

tl;博士;

您需要使用protojson.UnmarshaloneOf字段中正確獲取值。


我創建了以下原型定義

message Person {
  string name = 1;
  int32 id = 2;
  string email = 3;
  oneof avatar {
    string imageUrl = 4;
    bytes imageData = 5;
  }
}

然后我能夠創建一個 YAML 文件,可以正確讀取。

---
name: Harry Potter
id: 1
email: harry@potter.com
imageUrl: https://picsum.photos/id/1005/200

唯一的問題是,如果我執行以下操作,

yamlBytes, _ := ioutil.ReadFile("testdata/person.yaml")
person := &pb.Person{}
yaml.Unmarshal(yamlBytes, person)

就像您提到的那樣,未設置imageUrl的值。

您需要這樣做 - 首先將 YAML 轉換為 JSON,然后使用protojson.Unmarshal

yamlBytes, _ := ioutil.ReadFile("testdata/person.yaml")
person := &pb.Person{}
jsonBytes, _ := yaml.YAMLToJSON(yamlBytes)
protojson.Unmarshal(jsonBytes, person)

然后你就設置了正確的imageUrl值。

這是完整代碼的鏈接 - https://github.com/mbtamuli/GoLearnGo/tree/master/protobufs 您可以在這里看到它的實際效果 - https://replit.com/@mbtamuli/didactic-train

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM