golang proto中使用time类型:cannot use (type "time".Time) as type *timestamppb
2010 年 2 月 26 日
首先,引入对应timestamp包,这个是proto3的特性,类型直接是google.protobuf.Timestamp,他是一个时间戳
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']; };
然后编译成对应pb的go文件,这里要注意,我这里使用了gogo的模式,要选择好编译的模式
有些默认的是为了速度快,使用了gofast,但是他不支持其它gogoprotobuf extensions(这里的时间就是)。
go get github.com/gogo/protobuf/protoc-gen-gofast protoc --gofast_out=. myproto.proto
-
gogofast
、gogofaster
、gogoslick
: 更快的速度、更多的产生代码
gogofast
类似 gofast
,但是会导入gogoprotobuf.
gogofaster
类似 gogofast
, 不会产生 XXX_unrecognized
指针字段,可以减少垃圾回收时间。
gogoslick
类似 gogofaster
,但是可以增加一些额外的方法 gostring
和 equal
等等。
原文: https://colobu.com/2019/10/03/protobuf-ultimate-tutorial-in-go/
所以时间类型就应该使用gogo_out来生成
比如
bilibili中的api,如果有时间类型,就应该自己操作
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
生成的类型

image.png
这里注意,他这里是时间戳,并不是time类型,所以你要使用必须要转化一下。
使用到的包:地址:
https://godoc.org/github.com/golang/protobuf/ptypes#Timestamp
github.com/golang/protobuf/ptypes 代码:时间和时间戳相互转化 timetamp, err := ptypes.TimestampProto(time) time, err := ptypes.Timestamp(timetamp)
有疑问加站长微信联系(非本文作者)