教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 golang proto中使用time类型:cannot use (type "time".Time) as type *timestamppb

golang proto中使用time类型:cannot use (type "time".Time) as type *timestamppb

发布时间:2022-02-13   编辑:jiaochengji.com
教程集为您提供golang proto中使用time类型:cannot use (type "time".Time) as type *timestamppb等资源,欢迎您收藏本站,我们将为您提供最新的golang proto中使用time类型:cannot use (type "time".Time) as type *timestamppb资源

首先,引入对应timestamp包,这个是proto3的特性,类型直接是google.protobuf.Timestamp,他是一个时间戳

<pre><code class="lang-go">syntax = "proto3"; import "google/protobuf/timestamp.proto"; package demo.service.v1; option go_package = "api"; service Demo { rpc GetUser(HelloReq) returns (User) {}; }; } message HelloReq { string name = 1 [(gogoproto.moretags) = 'form:"name" validate:"required"']; } message User { string Id = 1 [(gogoproto.jsontag) = 'id']; string Name = 2 [(gogoproto.jsontag) = 'name']; google.protobuf.Timestamp CreateTime = 3 [(gogoproto.jsontag) = 'createtime']; }; </code></pre>

然后编译成对应pb的go文件,这里要注意,我这里使用了gogo的模式,要选择好编译的模式
有些默认的是为了速度快,使用了gofast,但是他不支持其它gogoprotobuf extensions(这里的时间就是)。

<pre><code class="lang-go">go get github.com/gogo/protobuf/protoc-gen-gofast protoc --gofast_out=. myproto.proto </code></pre><ul><li><code>gogofast</code>、<code>gogofaster</code>、<code>gogoslick</code>: 更快的速度、更多的产生代码</li></ul>

<code>gogofast</code>类似<code>gofast</code>,但是会导入gogoprotobuf.
<code>gogofaster</code>类似<code>gogofast</code>, 不会产生<code>XXX_unrecognized</code>指针字段,可以减少垃圾回收时间。
<code>gogoslick</code>类似<code>gogofaster</code>,但是可以增加一些额外的方法<code>gostring</code>和<code>equal</code>等等。
原文:https://colobu.com/2019/10/03/protobuf-ultimate-tutorial-in-go/

所以时间类型就应该使用gogo_out来生成
比如
bilibili中的api,如果有时间类型,就应该自己操作

<pre><code class="lang-go">protoc --proto_path=D:\mygo/src --proto_path=D:\mygo/pkg/mod/github.com/go-kratos/kratos@v0.6.1-0.20201211144700-5f8a93a41027/third_party --proto_path=D:\mygo\src\stb-kro\api --gogo_out=plugins=grpc:. api.proto </code></pre>

生成的类型

image.png

这里注意,他这里是时间戳,并不是time类型,所以你要使用必须要转化一下。

使用到的包:地址:https://godoc.org/github.com/golang/protobuf/ptypes#Timestamp

<pre><code class="lang-go">github.com/golang/protobuf/ptypes 代码:时间和时间戳相互转化 timetamp, err := ptypes.TimestampProto(time) time, err := ptypes.Timestamp(timetamp) </code></pre> 到此这篇关于“ golang proto中使用time类型:cannot use (type "time".Time) as type *timestamppb”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
golang proto中使用time类型:cannot use (type "time".Time) as type *timestamppb
PHP使用Beanstalkd实例详解
如何实现php时间轴 php时间轴实例参考
PHP计算上一个月的今天的代码
php计算上个月的今天的函数代码
Java、PHP、Python、Erlang、Golang 千万级内存数据插入、查询性能对比
golang log简单使用例子详解
Golang中time包用法及一些注意事项
php smtp发送邮件的函数
php header头信息应用举例

[关闭]
~ ~