Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Json 通过Go在协议缓冲区v3中的一个字段中使用结构_Json_Go_Protocol Buffers_Grpc - Fatal编程技术网

Json 通过Go在协议缓冲区v3中的一个字段中使用结构

Json 通过Go在协议缓冲区v3中的一个字段中使用结构,json,go,protocol-buffers,grpc,Json,Go,Protocol Buffers,Grpc,因此,尝试使用协议缓冲区v3并一起使用(对两者都是新的) 示例.proto syntax = "proto3"; package test; import "google/protobuf/timestamp.proto"; message Metadata { uint64 userID = 2; google.protobuf.Timestamp time= 3; } //SignOff when user logs out of Glory message Sig

因此,尝试使用协议缓冲区v3并一起使用(对两者都是新的)

示例.proto

syntax = "proto3";

package test;

import "google/protobuf/timestamp.proto";

message Metadata {
    uint64 userID = 2;
    google.protobuf.Timestamp time= 3; 
}

//SignOff when user logs out of Glory
message SignOff {
    Metadata metadata =1;
}

//SignOn when user logs into Glory
message SignOn {
    Metadata metadata =1;
}

message EventWrapper {
    oneof event {
        SignOff signOff = 1;
        SignOn signOn = 2;
    }
}
使用
protoc
转换并在Go中使用

now, _ := ptypes.TimestampProto(time.Now())
event := &pb_test.EventWrapper{
    Event: &pb_test.EventWrapper_SignOn{
        SignOn: &pb_test.SignOn{
            Metadata: &pb_test.Metadata{
                UserID: 1234,
                Time:   now,
            },
        },
    },
}
protoBytes, err := proto.Marshal(event)
if err != nil {
    log.Fatal(err)
}
log.Println(len(protoBytes) == 0)

jsonBytes, _ = json.MarshalIndent(event, "", "\t")
log.Println(string(jsonBytes))
输出显示JSON是正确的,但protobuf编码的字节数组是空的

{
    "Event": {
        "SignOn": {
            "metadata": {
                "userID": 1234,
                "time": {
                    "seconds": 1491143507,
                    "nanos": 654053400
                }
            }
        }
    }
}

其目的是让这些(
repeated*EventWrapper
)的数组通过gRPC沿线路发送,但单个的目前不起作用。protobuf没有说任何关于不允许使用结构的内容。有什么我遗漏的吗?

协议缓冲区文档中没有任何内容表明
oneof
不能是结构,事实上它为
union
字段生成结构

我建议使用,这是我个人在以前的商业项目中使用过的。具体来说,
使用protoc gen gogoslick

请参阅以了解如何安装必要的软件包,然后为您的项目运行以下程序

protoc --gogoslick_out=Mgoogle/protobuf/timestamp.proto=github.com/gogo/protobuf/types:. example.proto