golang protobuf从生成的json标记中删除omitempty标记 [英] golang protobuf remove omitempty tag from generated json tags

查看:1021
本文介绍了golang protobuf从生成的json标记中删除omitempty标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将google grpc与json代理一起使用.由于某些原因,我需要从* .pb.go文件中生成的结构中删除 omitempty 标记.

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 proto message like this

message Status {
  int32 code = 1;
  string message = 2;
}

生成的结构看起来像这样

The generated struct looks like this

type Status struct {
  Code int32 `protobuf:"varint,1,opt,name=code" json:"code,omitempty"`
  Message string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"`
}

但是我需要从生成的结构中删除 omitempty 标记.我该怎么办?

But My need is to remove the omitempty tag from the generated structs. How can i do this?

推荐答案

如果您使用的是grpc-gateway,并且您需要在json封送处理期间显示默认值,则可以在创建servemux时考虑添加以下选项

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

在grpc网关之外,如果要封送协议缓冲区消息,请使用 github.com/golang/protobuf/jsonpb 包而不是 encoding/json

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
}

这篇关于golang protobuf从生成的json标记中删除omitempty标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆