gpt4 book ai didi

go - 递归数据结构解码在 Go Lang Protobuf 中给出错误 "cannot parse invalid wire-format data"

转载 作者:行者123 更新时间:2023-12-05 04:30:09 89 4
gpt4 key购买 nike

操作系统和 protobuf 版本

go1.18.1 linux/amd64, github.com/golang/protobuf v1.5.2

简介

我正在尝试使用递归原型(prototype)定义。

.proto 文件

message AsyncConsensus {
int32 sender = 1;
int32 receiver = 2;
string unique_id = 3; // to specify the fall back block id to which the vote asyn is for
int32 type = 4; // 1-propose, 2-vote, 3-timeout, 4-propose-async, 5-vote-async, 6-timeout-internal, 7-consensus-external-request, 8-consensus-external-response, 9-fallback-complete
string note = 5;
int32 v = 6 ; // view number
int32 r = 7;// round number
message Block {
string id = 1;
int32 v = 2 ; // view number
int32 r = 3;// round number
Block parent = 4;
repeated int32 commands = 5;
int32 level = 6; // for the fallback mode
}
Block blockHigh = 8;
Block blockNew = 9;
Block blockCommit = 10;
}

下面是我编码和取消编码的方式

func (t *AsyncConsensus) Marshal(wire io.Writer) error {
data, err := proto.Marshal(t)
if err != nil {
return err
}
lengthWritten := len(data)
var b [8]byte
bs := b[:8]
binary.LittleEndian.PutUint64(bs, uint64(lengthWritten))
_, err = wire.Write(bs)
if err != nil {
return err
}
_, err = wire.Write(data)
if err != nil {
return err
}
return nil
}

func (t *AsyncConsensus) Unmarshal(wire io.Reader) error {

var b [8]byte
bs := b[:8]
_, err := io.ReadFull(wire, bs)
if err != nil {
return err
}
numBytes := binary.LittleEndian.Uint64(bs)
data := make([]byte, numBytes)
length, err := io.ReadFull(wire, data)
if err != nil {
return err
}
err = proto.Unmarshal(data[:length], t)
if err != nil {
return err
}
return nil
}

func (t *AsyncConsensus) New() Serializable {
return new(AsyncConsensus)
}

我的预期结果

当通过 TCP 编码并发送到同一进程时,它应该正确解码并生成正确的数据结构。

产生的错误

错误 “无法解析无效的有线格式数据”

附加信息

我尝试使用非递归 .proto 定义,之前从未遇到过这个问题。

最佳答案

我能想到的最愚蠢的错误是 wire.Write(bs) 写入的字节数不如 io.ReadFull(wire, bs)阅读 - 所以我只是确保在这两种情况下它们的返回值实际上都是 8。

那我对golang/protobuf不是很了解,不过我猜应该可以做到这一点。你不应该创建 go-code 然后调用它吗?我不确定如何调用它。

如果你认为这实际上是 protobuf 实现中的问题,有一些在线 protobuf-decoders 可以提供帮助。但他们有时会错误地解释流,递归模式可能就是这种情况,所以你必须小心。但至少他们帮我调试了不止一次dedis/protobuf包。

作为最后的手段,你可以用递归数据做一个最小的例子,检查它是否有效,然后慢慢添加字段直到它中断......

关于go - 递归数据结构解码在 Go Lang Protobuf 中给出错误 "cannot parse invalid wire-format data",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72126727/

89 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com