Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang protobuf remove omitempty tag from generated json tags

I am using google grpc with a json proxy. for some reason i need to remove the omitempty tags from the struct generated in the *.pb.go files.

if i have a proto message like this

message Status {   int32 code = 1;   string message = 2; } 

The generated struct looks like this

type Status struct {   Code int32 `protobuf:"varint,1,opt,name=code" json:"code,omitempty"`   Message string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"` } 

But My need is to remove the omitempty tag from the generated structs. How can i do this?

like image 944
sadlil Avatar asked Jan 11 '16 07:01

sadlil


People also ask

How do I get rid of omitEmpty in Protobuf?

you can copy the encoding/json package to your own folder for example my_json, and modify omitEmpty field to false, and use my_json. Marshal() to encode the struct to json string.

What does omitEmpty do in Golang?

The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.


2 Answers

If you are using grpc-gateway and you need the default values to be present during json marshaling, you may consider to add the following option when creating your servemux

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

Outside of grpc-gateway, if you want to marshal your protocul buffer message, use github.com/golang/protobuf/jsonpb package instead of encoding/json

func sendProtoMessage(resp proto.Message, w http.ResponseWriter) {     w.Header().Set("Content-Type", "application/json; charset=utf-8")     m := jsonpb.Marshaler{EmitDefaults: true}     m.Marshal(w, resp) // You should check for errors here } 
like image 146
DeeSilence Avatar answered Sep 18 '22 13:09

DeeSilence


A [more] portable solution:

Use sed to strip the tags after generating via protoc.

Example of what I actually use in my go:generate script after having generated the *.pb.go files:

ls *.pb.go | xargs -n1 -IX bash -c 'sed s/,omitempty// X > X.tmp && mv X{.tmp,}' 

Note: sed -i (inline-replacement) is not used here because that flag isn't portable between standard OS-X and Linux.

like image 28
Jay Taylor Avatar answered Sep 19 '22 13:09

Jay Taylor