gpt4 book ai didi

golang protobuf 从生成的 json 标签中删除 omitempty 标签

转载 作者:IT老高 更新时间:2023-10-28 13:06:28 72 4
gpt4 key购买 nike

我正在使用带有 json 代理的 google grpc。出于某种原因,我需要从 *.pb.go 文件中生成的结构中删除 omitempty 标记。

如果我有这样的原始消息

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

生成的结构是这样的

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 标记。我该怎么做?

最佳答案

如果您使用 grpc-gateway 并且需要在 json 编码期间提供默认值,则可以考虑在创建 servermux 时添加以下选项

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

在 grpc-gateway 之外,如果你想编码你的 protocul 缓冲区消息,请使用 github.com/golang/protobuf/jsonpb 包而不是 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 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34716238/

72 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com