Search code examples
goprotocol-buffersgrpc-gateway

Not able to generating empty array/slice of golang code using protobuf


We want to return one object/struct with one property as empty list/array/slice in golang to client(browser). from the go code we are returning empty slice of len=0 and capacity=0, but through protobuf this key is getting deleted or set as a nil and removed.

protobuf code

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",
    }

I am getting actual output as {api: "v1"} but expected should come as {api: "v1",todos:[]}

Please help/suggest us in fixing the protobuf or golang syntax.


Solution

  • Your array field gets lost when grpc-gateway serializes the proto struct to json with jsonpb serializer.

    Fortunately the gateway exposes a way to configure the jsonpb serializer when setting up the gateway:

    mux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{ EmitDefaults:true}))
    

    The &runtime.JSONPb{ EmitDefaults:true} option should do what you want.