为了账号安全,请及时绑定邮箱和手机立即绑定

如何通过 grpcurl 发送时间戳?

如何通过 grpcurl 发送时间戳?

Go
qq_笑_17 2022-06-06 15:25:25
我正在使用 GRPC/proto-buffers 在 GoLang 中编写我的第一个 API 端点。我对 GoLang 比较陌生。以下是我为测试用例编写的文件package my_packageimport (    "context"    "testing"    "github.com/stretchr/testify/require"    "google.golang.org/protobuf/types/known/structpb"    "github.com/MyTeam/myproject/cmd/eventstream/setup"    v1handler "github.com/MyTeam/myproject/internal/handlers/myproject/v1"    v1interface "github.com/MyTeam/myproject/proto/.gen/go/myteam/myproject/v1")func TestEndpoint(t *testing.T) {    conf := &setup.Config{}    // Initialize our API handlers    myhandler := v1handler.New(&v1handler.Config{})    t.Run("Success", func(t *testing.T) {        res, err := myhandler.Endpoint(context.Background(), &v1interface.EndpointRequest{            A: "S",            B: &structpb.Struct{                Fields: map[string]*structpb.Value{                    "T": &structpb.Value{                        Kind: &structpb.Value_StringValue{                            StringValue: "U",                        },                    },                    "V": &structpb.Value{                        Kind: &structpb.Value_StringValue{                            StringValue: "W",                        },                    },                },            },            C: &timestamppb.Timestamp{Seconds: 1590179525, Nanos: 0},        })        require.Nil(t, err)        // Assert we got what we want.        require.Equal(t, "Ok", res.Text)    })}上面的测试用例似乎工作正常。但我想用 grpcurl 模拟同样的测试用例。这有效:grpcurl -d '{"a": "S", "b": {"T": "U", "V": "W"}}' -plaintext localhost:11000 myteam.myproject.v1.MyProject/Endpoint但是当我尝试以下操作时,它失败了:grpcurl -d '{"a": "S", "b": {"T": "U", "V": "W"}, "c": "1590179525"}' -plaintext localhost:11000 myteam.myproject.v1.MyProject/EndpointError invoking method "myteam.myproject.v1.MyProject/Endpoint": error getting request data: bad Timestamp: parsing time "1590179525" as "2006-01-02T15:04:05.999999999Z07:00": cannot parse "179525" as "-"如何通过 grpcurl 发送时间戳?
查看完整描述

1 回答

?
慕容3067478

TA贡献1773条经验 获得超3个赞

google.protobuf.Timestamp的底层类型是timestamppb.Timestamp

文档说明了 json 表示的格式:

JSON 映射

在 JSON 格式中,Timestamp 类型被编码为RFC 3339格式的字符串。也就是说,格式为“{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z”,其中 {year} 始终使用四位数字表示,而 { month}、{day}、{hour}、{min} 和 {sec} 分别用零填充到两位数。小数秒,最多可达 9 位(即分辨率高达 1 纳秒),是可选的。“Z”后缀表示时区(“UTC”);时区是必需的。proto3 JSON 序列化程序在打印 Timestamp 类型时应始终使用 UTC(如“Z”所示),并且 proto3 JSON 解析器应该能够同时接受 UTC 和其他时区(如偏移量所示)。

例如,“2017-01-15T01:30:15.01Z”对 2017 年 1 月 15 日 01:30 UTC 过去 15.01 秒进行编码。

这也可以在您收到的错误消息中看到:

将“1590179525”解析为“2006-01-02T15:04:05.999999999Z07:00”:无法将“179525”解析为“-”

这是 Go 的标准时间解析,如Time.Parse中所述。

因此,您应该传递字符串,而不是传递自纪元以来的秒数字符串:

2020-05-22T20:32:05Z

上面的字符串是通过运行获得的:

fmt.Println(time.Unix(1590179525, 0).Format(time.RFC3339))


查看完整回答
反对 回复 2022-06-06
  • 1 回答
  • 0 关注
  • 211 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号