如何在 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知识!
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
477 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习