Home > Backend Development > Golang > How to Remove `omitempty` Tags from GoLang Protobuf JSON Output?

How to Remove `omitempty` Tags from GoLang Protobuf JSON Output?

DDD
Release: 2024-12-30 05:55:09
Original
356 people have browsed it

How to Remove `omitempty` Tags from GoLang Protobuf JSON Output?

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,
    }),
)
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template