登录
首页 >  Golang >  Go问答

如何在 Golang 中将“omitempty”与 protobuf 时间戳一起使用

来源:stackoverflow

时间:2024-03-16 23:18:28 124浏览 收藏

在 Go 语言中使用 protobuf 时间戳时,使用“omitempty”标签可以防止空值字段在序列化为 JSON 时被发送。然而,当将空 time.Time 对象转换为 protobuf 时间戳时,会产生负秒值,导致“omitempty”标签失效。为了解决这个问题,建议在转换时使用 commtime=nil; 语句,该语句将创建一个零值 protobuf 时间戳,从而避免发送空值字段。

问题内容

我的结构中有一个名为 expiretime 的可选字段。它有一个 time.time 类型和一个 json:"expire_time,omitempty" 标签,当它为空时不发送它。这部分工作得很好。

当我想通过 grpc 使用相同的字段时,在将其转换为 protobuf 时间戳格式时遇到了问题。

type timestamp struct {

    // represents seconds of utc time since unix epoch
    // 1970-01-01t00:00:00z. must be from 0001-01-01t00:00:00z to
    // 9999-12-31t23:59:59z inclusive.
    seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"`
    // non-negative fractions of a second at nanosecond resolution. negative
    // second values with fractions must still have non-negative nanos values
    // that count forward in time. must be from 0 to 999,999,999
    // inclusive.
    nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"`
    // contains filtered or unexported fields
}
ExpireTime *timestamppb.Timestamp `protobuf:"bytes,1,opt,name=expire_time,json=expireTime,proto3" json:"expire_time,omitempty"`

问题在于,空的 time.time{} 对象将转换为与 0001-01-01t00:00:00z 相对应的负 seconds 值。在这种情况下,不会应用 omitempty 标志,因为该值未清零。当该字段实际上为空时,我该怎么做才能省略该字段?谢谢!


正确答案


正如你所说,time.time{} 转换为 0001-01-01t00:00:00z;这个 is working as intended。请注意,您还需要小心地在 opposite direction 中进行转换(零 timestamp 将变为 1970-01-01t00:00:00z)。

但是,通常 timestamp 将成为消息的一部分,例如:

message mymessage{
   google.protobuf.timestamp  comm_time = 1;
}

通过 protoc 运行此命令将导致类似以下结果:

type mymessage struct {
    state         protoimpl.messagestate
    sizecache     protoimpl.sizecache
    unknownfields protoimpl.unknownfields

    commtime *timestamppb.timestamp `protobuf:"bytes, 1,opt,name=comm_time,json=commtime,proto3" json:"comm_time,omitempty"`
}

这意味着您应该能够使用 commtime=nil; 获得您正在寻找的结果;例如

sourceTime := time.Time{}  // Whatever time you want to encode
var commTime *timestamp.Timestamp
if !sourceTime.IsZero() {
        commTime = timestamppb.New(sourceTime)
}

msg := MyMessage{
   CommTime: commTime,
}

好了,本文到此结束,带大家了解了《如何在 Golang 中将“omitempty”与 protobuf 时间戳一起使用》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>