我正在使用GRPC/proto缓冲区在GoLang中编写我的第一个API端点。我对GoLang相当陌生。下面是我为测试用例编写的文件
package my_package
import (
"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: ×tamppb.Timestamp{Seconds: 1590179525, Nanos: 0},
})
require.Nil(t, err)
// Assert we got what we want.
require.Equal(t, "Ok", res.Text)
})
}
EndpointRequest
对象是如何在上面包含的v1.go
文件中定义的:
// An v1 interface Endpoint Request object.
message EndpointRequest {
// a is something.
string a = 1 [(validate.rules).string.min_len = 1];
// b can be a complex object.
google.protobuf.Struct b = 2;
// c is a timestamp.
google.protobuf.Timestamp c = 3;
}
上面的测试用例似乎运行良好。
但我想用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/Endpoint
Error 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发送时间戳?
发布于 2020-05-23 10:05:49
google.protobuf.Timestamp的基础类型是timestamppb.Timestamp。
文档详细说明了json表示的格式:
JSON映射 在JSON格式中,时间戳类型被编码为RFC 3339格式的字符串。也就是说,格式为"{year}-{month}-{day}T{hour}:{min}:{sec}.{frac_sec}Z“,其中{day}总是用四位数表示,而{月份}、{day}、{ That }、{min}和{sec}是零填充到两个数字上的。小数秒可以达到9位数(即高达1纳秒的分辨率),是可选的。"Z“后缀表示时区("UTC");需要时区。在打印时间戳类型时,proto3 JSON序列化程序应该始终使用UTC (如“Z”所示),proto3 JSON解析器应该能够同时接受UTC和其他时区(如偏移量所示)。 例如," 2017 -01-15T01:30:15.01Z“编码在2017年1月15日世界协调时01:30之后的15.01秒。
这也可以在您收到的错误消息中看到:
解析时间"1590179525“为”2006-01-02T15:04:05.999999999999999Z07:00“:无法将"179525”解析为"-“
这是Go的标准时间解析,如Time.Parse中所述。
因此,您应该传递字符串,而不是从时代开始传递一个秒的字符串:
2020-05-22T20:32:05Z
以上字符串是通过运行以下命令获得的:
fmt.Println(time.Unix(1590179525, 0).Format(time.RFC3339))
https://stackoverflow.com/questions/61970241
复制相似问题