Protobuffers和Golang – 将编组的结构写出并读取回来

huangapple go评论72阅读模式
英文:

Protobuffers and Golang --- writing out marshal'ed structs and reading back in

问题

有没有一种普遍接受的“正确”方法来将协议缓冲区消息从文件中写入并读取回来?

我一直在一个小项目上工作,该项目使用gRPC在本地模拟完整的网络,并尝试添加写入/读取文件的功能,以便在再次启动时可以保存状态并从上次的状态开始。我天真地以为这些消息会保持在一行上:

Sees chain of length 3

这是我写的调试消息;但是,

$ wc test.dat
   7    8 2483 test.dat

所以,我想可能有额外的4个换行符... 是否有一种我可以使用的分隔方法?还是我需要自己想出一个方法?我意识到这很简单,但在我看来,我只能以概率的方式保证<<<<DELIMIT>>>>或其他任何内容永远不会出现,使我回到原点。

英文:

Is there a generally accepted "correct" way for writing out and reading back in marshaled protocol buffer messages from a file?

I've been working on a smaller project that simulates a full network locally with gRPC and am trying to add writing to/ reading from files s.t. I can save state and start from there when its launched again. It seems I was naive in assuming these would remain on a single line:

Sees chain of length 3

from debugging messages I've written; but,

$ wc test.dat
   7    8 2483 test.dat

So, I suppose there are an extra 4 newline's... Is there a method of delimiting these that I can use? or do I need to come up with one on my own? I realize this is straightforward, but in my mind, I can only probabilistically guarantee that &lt;&lt;&lt;&lt;DELIMIT&gt;&gt;&gt;&gt; or whatever will never show up and put me back at square 1.

答案1

得分: 0

使用proto.Marshal/Unmarshal:

这样你可以模拟(最接近)接收消息的过程,同时避免其他Marshal方法带来的副作用。

另一种方法是将其转储为[]byte,然后重新读取。

英文:

Use proto.Marshal/Unmarshal:

That way you simulate (closest) to receiving the message while avoiding side effects from other Marshal methods.

Alternative: Dump it as []byte and reread it.

huangapple
  • 本文由 发表于 2022年7月23日 05:43:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/73086348.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定