go data_error ai_generated true

proto:无法解析无效的 wire-format 数据

proto: cannot parse invalid wire-format data

ID: go/protobuf-cannot-unmarshal-wire-type

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-03-22首次发现

版本兼容性

版本状态引入弃用备注
google.golang.org/protobuf v1.28+ active

根因分析

传给 proto.Unmarshal 的字节切片不是目标消息的有效 protobuf 编码——通常是客户端与服务端使用了不同的 .proto 定义,或者数据根本不是 protobuf。

English

The byte slice passed to proto.Unmarshal is not a valid protobuf encoding for the target message — often because the client and server use different .proto definitions or the payload is not protobuf at all.

generic

解决方案

  1. 90% 成功率
    Verify the sender and receiver share the exact same .proto file. Regenerate stubs and compare descriptor hashes:
    import "google.golang.org/protobuf/reflect/protoreflect"
    desc := (&pb.MyMsg{}).ProtoReflect().Descriptor()
    log.Printf("msg=%s pkg=%s", desc.FullName(), desc.ParentFile().Package())
  2. 80% 成功率
    Wrap Unmarshal with a length check and hex dump on failure to identify the payload:
    if err := proto.Unmarshal(data, msg); err != nil {
      log.Printf("unmarshal failed: %v, first16=%x", err, data[:min(16,len(data))])
      return err
    }

无效尝试

常见但无效的做法:

  1. 95% 失败

    Wire-format mismatch is a schema problem, not a size problem; retrying with more memory won't help.

  2. 85% 失败

    If the wire bytes are actually protobuf, JSON parsing fails; if they're JSON, the sender is misconfigured.