登录
首页 >  Golang >  Go问答

出现未知字段错误时解析带有修改嵌入类型的消息

来源:stackoverflow

时间:2024-02-25 18:48:24 347浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《出现未知字段错误时解析带有修改嵌入类型的消息》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

给定一个这样的原型:

message request {
    uint64 account_id = 1;
    message foo{
        uint64 foo_id = 1;
    }
    repeated foo foos = 2;

当我添加一个名为 bar_id 的字段时

message Request {
    uint64 account_id = 1;
    message Foo{
        uint64 foo_id = 1;
        uint64 bar_id = 2;
    }
    repeated Foo foos = 2;

通过 proto.unmarshaltext(msg, request) 使用旧的 client 进行反序列化时出现错误。错误是 servicea.request_foo 中的 unknown 字段名称“bar_id”。

我知道 proto-3 中的 unknown 字段 处理发生了很多变化,但这不是预期的,因为它似乎违反了前向兼容性(新服务器向旧客户端发送请求)。这与使用嵌入类型有关吗?在不强制客户端更新的情况下更新服务器的最佳方法是什么?


正确答案


您似乎正在使用已弃用的 github.com/golang/protobuf。使用google.golang.org/protobuf/encoding/prototext

upd:使用 DiscardUnknown

(prototext.unmarshaloptions{discardunknown: true}).unmarshal(b, msg)

pb.proto:

syntax = "proto3";

// protoc --go_out=. *.proto

package pb;

option go_package = "./pb";

message requestold {
    uint64 account_id = 1;
    message foo{
        uint64 foo_id = 1;
    }
    repeated foo foos = 2;
}

message requestnew {
    uint64 account_id = 1;
    message foo{
        uint64 foo_id = 1;
        uint64 bar_id = 2;
    }
    repeated foo foos = 2;
}

功能:

import "google.golang.org/protobuf/encoding/prototext"

// marshal old message
msgold := &pb.requestold{
    accountid: 1,
    foos: []*pb.requestold_foo{
        {
            fooid: 2,
        },
    },
}

log.println("old:", msgold.string())

bold, err := prototext.marshal(msgold)
if err != nil {
    panic(err)
}

// unmarshal to new message
msgnew := &pb.requestnew{}
if err := prototext.unmarshal(bold, msgnew); err != nil {
    panic(err)
}

log.println("new:", msgnew.string())

输出:

2021/04/07 old: account_id:1  foos:{foo_id:2}
2021/04/07 new: account_id:1  foos:{foo_id:2}

终于介绍完啦!小伙伴们,这篇关于《出现未知字段错误时解析带有修改嵌入类型的消息》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>