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
Mary-Kate OlsenOriginal
2024-12-03 22:55:12854browse

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}))

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
}

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!

Statement:
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