golang protobuf remove omitempty tag from generated json tags

后端 未结 7 1439
余生分开走
余生分开走 2021-02-04 00:00

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 pr

7条回答
  •  感动是毒
    2021-02-04 00:25

    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
    }
    

提交回复
热议问题