登录
首页 >  Golang >  Go问答

Protobuf 解组是一样任何情况

来源:stackoverflow

时间:2024-03-01 18:09:27 102浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《Protobuf 解组是一样任何情况》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我有一个使用 any 类型的原型 api

message document {
    documentmeta meta = 1;
    bytes data = 2;
    google.protobuf.any details = 3;
}

在客户端上,我创建了一条名为 dog 的消息,并创建了详细信息字段,如下所示:

dog1 := events2.dog{
    name: "leo",
    id:   1,
}
var dst anypb.any
err = anypb.marshalfrom(&dst, &dog1, proto.marshaloptions{})

包含 dog proto 的 .pb 文件也会复制到服务器中。

如果我在服务器中打印文档,它会提供正确的信息

any:type_url:"type.googleapis.com/com.test.eventbus.pb.events.dog" value:"\n\x03leo\x10\x01"

在服务器端,我在不提供特定 proto.message 类型(dog)的情况下进行解组

basicDog, err := anypb.UnmarshalNew(doc.GetDetails(), proto.UnmarshalOptions{})

unmarshalnew 因 proto 失败:未找到

  1. 我不会在解组期间提供特定类型,因为客户端可以发送在应用程序启动期间未定义的任何类型的消息。
  2. 因此,客户端生成一个新的 proto 文件,为 go 生成 .pb 并将该 .go 文件复制到服务器内。

如何在使用 unmarshalany() 方法时在服务器端使用 .pb 文件?


正确答案


尝试使用 google.protobuf.value

原始文件:

syntax = "proto3";

package mediation.common;

option go_package = ".;common";

import "google/protobuf/struct.proto";

message model {
  google.protobuf.value any = 2;
}

使用:

package common

import (
    "encoding/json"
    "testing"

    "google.golang.org/protobuf/types/known/structpb"
)

type Dog struct {
    Id   int
    Name string
}

func TestAny(t *testing.T) {
    data := map[string]interface{}{
        "id":   1,
        "name": "kitty",
    }

    s, _ := structpb.NewValue(data)
    newData := s.GetStructValue()

    m := Model{Any: structpb.NewStructValue(newData)}

    var dog Dog
    unmarshal(m.GetAny(), &dog)
    t.Log(dog)

    var mm map[string]interface{}
    unmarshal(m.GetAny(), &mm)
    t.Log(mm)
}

func unmarshal(p *structpb.Value, o interface{}) error {
    byt, _ := p.MarshalJSON()
    return json.Unmarshal(byt, o)
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

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