Home > Backend Development > Golang > How Can I Prevent OmitEmpty JSON Tags When Generating Protobuf Messages in Go?

How Can I Prevent OmitEmpty JSON Tags When Generating Protobuf Messages in Go?

Mary-Kate Olsen
Release: 2024-12-03 22:55:12
Original
849 people have browsed it

How Can I Prevent OmitEmpty JSON Tags When Generating Protobuf Messages in Go?

Generating Proto Buffs Without OmitEmpty JSON Tags in Go

When using gRPC with a JSON proxy, omitempty tags are automatically added to generated structs. This can cause issues when marshaling messages, as default values are not included in the JSON payload.

To overcome this, consider adding the following option to your ServeMux:

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

This will ensure that default values are always present in the generated JSON.

Alternatively, you can use the google.golang.org/protobuf/encoding/protojson package to marshal your protocol buffer messages. This package provides more control over the encoding process and allows you to specify that default values should be emitted:

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) // Check for errors here
}
Copy after login

Note: google.golang.org/protobuf has replaced the deprecated github.com/golang/protobuf and its jsonpb package.

The above is the detailed content of How Can I Prevent OmitEmpty JSON Tags When Generating Protobuf Messages in Go?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template