This repository has been archived by the owner on Apr 27, 2021. It is now read-only.
forked from snormore/gosky
-
Notifications
You must be signed in to change notification settings - Fork 2
/
event.go
79 lines (67 loc) · 1.83 KB
/
event.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package sky
import (
"errors"
"fmt"
"time"
)
//------------------------------------------------------------------------------
//
// Typedefs
//
//------------------------------------------------------------------------------
// An Event is a timestamped hash of data.
type Event struct {
Timestamp time.Time
Data map[string]interface{}
}
//------------------------------------------------------------------------------
//
// Constructor
//
//------------------------------------------------------------------------------
func NewEvent(timestamp time.Time, data map[string]interface{}) *Event {
return &Event{
Timestamp: timestamp,
Data: data,
}
}
//------------------------------------------------------------------------------
//
// Methods
//
//------------------------------------------------------------------------------
//--------------------------------------
// Serialization
//--------------------------------------
// Encodes an event into an untyped map.
func (e *Event) Serialize() map[string]interface{} {
return map[string]interface{}{
"timestamp": FormatTimestamp(e.Timestamp),
"data": e.Data,
}
}
// Decodes an event from an untyped map.
func (e *Event) Deserialize(obj map[string]interface{}) error {
if obj == nil {
return errors.New("sky.Event: Unable to deserialize nil.")
}
// Deserialize "timestamp".
if str, ok := obj["timestamp"].(string); ok {
if timestamp, err := ParseTimestamp(str); err == nil {
e.Timestamp = timestamp
} else {
return err
}
} else {
return fmt.Errorf("sky.Event: Invalid timestamp: %v", obj["timestamp"])
}
// Deserialize "data".
if data, ok := obj["data"].(map[string]interface{}); ok {
e.Data = data
} else if data == nil {
e.Data = map[string]interface{}{}
} else {
return fmt.Errorf("sky.Event: Invalid data: %v", obj["data"])
}
return nil
}