forked from vmihailenco/msgpack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_registerExt_test.go
62 lines (51 loc) · 1.31 KB
/
example_registerExt_test.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
package msgpack_test
import (
"encoding/binary"
"fmt"
"time"
"github.com/vmihailenco/msgpack/v4"
)
func init() {
msgpack.RegisterExt(1, (*EventTime)(nil))
}
// https://github.com/fluent/fluentd/wiki/Forward-Protocol-Specification-v1#eventtime-ext-format
type EventTime struct {
time.Time
}
var _ msgpack.Marshaler = (*EventTime)(nil)
var _ msgpack.Unmarshaler = (*EventTime)(nil)
func (tm *EventTime) MarshalMsgpack() ([]byte, error) {
b := make([]byte, 8)
binary.BigEndian.PutUint32(b, uint32(tm.Unix()))
binary.BigEndian.PutUint32(b[4:], uint32(tm.Nanosecond()))
return b, nil
}
func (tm *EventTime) UnmarshalMsgpack(b []byte) error {
if len(b) != 8 {
return fmt.Errorf("invalid data length: got %d, wanted 8", len(b))
}
sec := binary.BigEndian.Uint32(b)
usec := binary.BigEndian.Uint32(b[4:])
tm.Time = time.Unix(int64(sec), int64(usec))
return nil
}
func ExampleRegisterExt() {
b, err := msgpack.Marshal(&EventTime{time.Unix(123456789, 123)})
if err != nil {
panic(err)
}
var v interface{}
err = msgpack.Unmarshal(b, &v)
if err != nil {
panic(err)
}
fmt.Println(v.(*EventTime).UTC())
tm := new(EventTime)
err = msgpack.Unmarshal(b, tm)
if err != nil {
panic(err)
}
fmt.Println(tm.UTC())
// Output: 1973-11-29 21:33:09.000000123 +0000 UTC
// 1973-11-29 21:33:09.000000123 +0000 UTC
}