Time datatype mismatch between Golang cloudEvent and proto

337 Views Asked by At

I am creating a proto file (and following cloudEvents standards).

syntax = "proto3";
option go_package = "/events";

import "google/protobuf/timestamp.proto";
import "google/protobuf/any.proto";

message Event {
    string specversion = 2;
    string type = 3;
    string source = 4;
    string id = 5;
    google.protobuf.Timestamp time = 6;
    google.protobuf.Any data = 7;
    map<string, CloudEventAttributeValue> attributes = 8;
    string datacontenttype = 9;
    string test = 10;
}

It works well between client and server. We also want to make sure that this object is totally conformant to cloudevents. To test this out If I tried marshalling this object using json.marshal() and then unmarshal using json.unmarshal into a cloudEvent object. In this test deseriallization is breaking due to time field datatype mismatch between proto object and cloudEvents.

bytes, _ := json.Marshal(ev)
fmt.Println(string(bytes))

e := cloudevents.NewEvent()
json.Unmarshal(bytes, &e)

But if I remove the time field, everything works well. Any idea what am I missing?

2

There are 2 best solutions below

1
On

Time really should be third hardest thing in programming (link).

I'm less familiar with Cloud Events but I suspect there's no requirement that you be able to use default marshalling. It seems that you'd be satisfied with a definitive way to manage this mapping?

Please include in your question the JSON that is produced. What is the discrepancy? Are you getting string representations of say RFC3339 format and you want e.g. UNIX epoch?

You may need a custom marshaller that converts the proto Timestamp into a UNIX epoch int, for example, for Cloud Events.

0
On

Using protojson.Marshal in place of json.Marshal solved this issue. Internally it passes marshallingoption required to marshal from proto standards.

https://github.com/golang/protobuf/issues/1355