-
Notifications
You must be signed in to change notification settings - Fork 7
/
optionalday.go
56 lines (46 loc) · 964 Bytes
/
optionalday.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
package kafkaavro
import (
"encoding/json"
"time"
"github.com/pkg/errors"
)
type OptionalDay struct {
Valid bool
Time time.Time
}
func NewOptionalDay(t time.Time, valid bool) OptionalDay {
return OptionalDay{
Valid: valid,
Time: t,
}
}
func (od *OptionalDay) FromNative(data interface{}) error {
// value is null
if data == nil {
od.Valid = false
od.Time = time.Unix(0, 0)
return nil
}
// otherwise it is a record with a field "int"
m, ok := data.(map[string]interface{})
if !ok {
return errors.New("OptionalDay data not a record")
}
val, ok := m["int.date"]
if !ok {
return errors.New("OptionalDay record missing int field")
}
t, ok := val.(time.Time)
if !ok {
return errors.New("OptionalDay value type mismatch")
}
od.Valid = true
od.Time = t
return nil
}
func (od OptionalDay) MarshalJSON() ([]byte, error) {
if !od.Valid {
return []byte("null"), nil
}
return json.Marshal(od.Time.Format("2006-01-02"))
}