美文网首页
golang proto中使用time类型:cannot use

golang proto中使用time类型:cannot use

作者: 哆啦在这A梦在哪 | 来源:发表于2021-01-07 17:06 被阅读0次

    首先,引入对应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
    
    • gogofastgogofastergogoslick: 更快的速度、更多的产生代码

    gogofast类似gofast,但是会导入gogoprotobuf.
    gogofaster类似gogofast, 不会产生XXX_unrecognized指针字段,可以减少垃圾回收时间。
    gogoslick类似gogofaster,但是可以增加一些额外的方法gostringequal等等。
    原文: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)
    

    相关文章

      网友评论

          本文标题:golang proto中使用time类型:cannot use

          本文链接:https://www.haomeiwen.com/subject/fsgzoktx.html