我有一个使用jhump/protoreflect创建的动态原型。当我尝试使用gogo jsonpb编组 proto 对象时,我最终遇到了下面提到的错误。
代码:
import "github.com/gogo/protobuf/types"
...
p := protoparse.Parser{
Accessor: protoparse.FileContentsFromMap(map[string]string{
"foo/bar.proto": `
syntax = "proto3";
package foo;
message Bar {
string name = 1;
int32 id = 2;
}
`,
}),
ImportPaths: []string{"foo"},
}
fds, err := p.ParseFilesButDoNotLink("foo/bar.proto")
if err != nil {
return nil, err
}
linkedFiles, err := desc.CreateFileDescriptors(fds)
if err != nil {
return nil, err
}
fd := linkedFiles["foo/bar.proto"]
md := fd.FindMessage("foo.Bar")
dm := dynamic.NewMessage(md)
proto.RegisterType((*dynamic.Message)(nil), "foo.Bar")
golang_proto.RegisterType((*dynamic.Message)(nil), "foo.Bar")
dm = dynamic.NewMessage(md)
dm.SetFieldByNumber(1, "kishore")
dm.SetFieldByNumber(2, int32(123))
a1, err := types.MarshalAny(dm)
if err != nil {
return nil, err
}
fmt.Printf("Create Any Marshalled Data is : %v\n", a1)
resp := &data.CreateAnyResponse{Object: a1}
fmt.Printf("Final Resp is : %v\n", resp)
resolver := dynamic.AnyResolver(nil, fd)
golangMarshaller := golang_jsonpb.Marshaler{AnyResolver: resolver}
js1, err := golangMarshaller.MarshalToString(resp)
if err != nil {
fmt.Printf("Error is is : %v\n", err)
return nil, err
}
fmt.Printf("After Marshal Resp1 is : %v\n", js1)
到目前为止,它可以工作并打印After Marshal Resp1 is : {"object":{"@type":"type.googleapis.com/foo.Bar","id":123,"name":"kishore"}}
,因为所有对象都定义为 Go protobuf。但是,当我使用 gogo marshaler 尝试类似的方法时(因为我的 grpc 运行时使用 gogo),我得到下面提到的错误。
jsm := &gateway.JSONPb{
OrigName: true,
EnumsAsInts: false,
EmitDefaults: true,
AnyResolver: resolver,
}
js, err := jsm.Marshal(resp)
if err != nil {
fmt.Printf("Error is is : %v\n", err)
return nil, err
}
fmt.Printf("After Marshal Resp is : %s\n", string(js))
错误:
cannot use resolver (type "github.com/golang/protobuf/jsonpb".AnyResolver) as type "github.com/gogo/protobuf/jsonpb".AnyResolver in field value:
"github.com/golang/protobuf/jsonpb".AnyResolver does not implement "github.com/gogo/protobuf/jsonpb".AnyResolver (wrong type for Resolve method)
have Resolve(string) ("github.com/golang/protobuf/proto".Message, error)
want Resolve(string) ("github.com/gogo/protobuf/proto".Message, error)
结构CreateAnyResponse
:
message CreateAnyResponse {
google.protobuf.Any object = 1;
}
我尝试在本地克隆和自定义AnyResolver并使用gogo
proto.Message,但在编组后数据未编组
After Marshal Resp is : {"object":{"@type":"type.googleapis.com/foo.Bar"}}
有没有办法使用gogo
jsonpb marshaller 转换这些动态原型?