Removing Omitempty Tag from Generated JSON Tags in GoLang Protobuf
In Google gRPC with a JSON proxy, you may encounter a scenario where you need to remove the omitempty tags from the generated structs in .pb.go files. This requirement arises to ensure the presence of default values during JSON marshaling.
To address this issue, you can implement the following strategies:
For grpc-gateway Users:
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:
Utilize the google.golang.org/protobuf/encoding/protojson package for marshaling your Protobuf message. This package has replaced the deprecated github.com/golang/protobuf/jsonpb package.
func sendProtoMessage(resp proto.Message, w http.ResponseWriter) { w.Header().Set("Content-Type", "application/json; charset=utf-8") m := protojson.Marshaler{EmitDefaults: true} m.Marshal(w, resp) // Handling of potential errors is recommended }
By following these approaches, you can effectively remove the omitempty tag from the generated JSON tags in GoLang Protobuf, ensuring the inclusion of default values during JSON marshaling.
The above is the detailed content of How to Remove `omitempty` Tags from GoLang Protobuf JSON Output?. For more information, please follow other related articles on the PHP Chinese website!