无法使用 protobuf 生成空 array/slice 的 golang 代码
Not able to generating empty array/slice of golang code using protobuf
我们想要 return 一个 object/struct 和一个 属性 作为空 list/array/slice 在 golang 中到客户端(浏览器)。
在 go 代码中,我们 returning 了 len=0 和 capacity=0 的空切片,但是通过 protobuf,这个键被删除或设置为 nil 并被删除。
syntax = "proto3";
package version1;
message ToDo {
int64 id = 1 ;
string title = 2;
}
message ReadAllResponse{
repeated ToDo toDos = 1 ;
}
golang code:
list := make([]*version1.ToDo, 0) //[]*version1.ToDo{}
output:= version1.ReadAllResponse{
ToDos: list,
Api: "v1",
}
我得到的实际输出是 {api: "v1"}
,但预期应该是 {api: "v1",todos:[]}
请help/suggest我们修复 protobuf 或 golang 语法。
当 grpc-gateway 使用 jsonpb 序列化程序将原型结构序列化为 json 时,您的数组字段会丢失。
幸运的是,网关公开了一种在设置网关时配置 jsonpb 序列化程序的方法:
mux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{ EmitDefaults:true}))
&runtime.JSONPb{ EmitDefaults:true}
选项应该可以满足您的需求。
我们想要 return 一个 object/struct 和一个 属性 作为空 list/array/slice 在 golang 中到客户端(浏览器)。 在 go 代码中,我们 returning 了 len=0 和 capacity=0 的空切片,但是通过 protobuf,这个键被删除或设置为 nil 并被删除。
syntax = "proto3";
package version1;
message ToDo {
int64 id = 1 ;
string title = 2;
}
message ReadAllResponse{
repeated ToDo toDos = 1 ;
}
golang code:
list := make([]*version1.ToDo, 0) //[]*version1.ToDo{}
output:= version1.ReadAllResponse{
ToDos: list,
Api: "v1",
}
我得到的实际输出是 {api: "v1"}
,但预期应该是 {api: "v1",todos:[]}
请help/suggest我们修复 protobuf 或 golang 语法。
当 grpc-gateway 使用 jsonpb 序列化程序将原型结构序列化为 json 时,您的数组字段会丢失。
幸运的是,网关公开了一种在设置网关时配置 jsonpb 序列化程序的方法:
mux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{ EmitDefaults:true}))
&runtime.JSONPb{ EmitDefaults:true}
选项应该可以满足您的需求。