我使用任何类型的proto。
message Document {
DocumentMeta meta = 1;
bytes data = 2;
google.protobuf.Any details = 3;
}
在客户机上,我创建了一个名为Dog的消息,并创建了details字段,如下所示:
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: not found
一起失败
如何在服务器端使用.pb文件,同时使用unmarshalAny()方法?
发布于 2022-08-18 02:39:45
试着使用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)
}
https://stackoverflow.com/questions/73385231
复制相似问题