-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunmarshal_example_test.go
93 lines (79 loc) · 1.78 KB
/
unmarshal_example_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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package darknut_test
import (
"fmt"
"time"
"github.com/google/uuid"
"github.com/ttab/darknut"
"github.com/ttab/newsdoc"
)
type exampleItem struct {
UUID uuid.UUID `newsdoc:"uuid"`
Meta exampleBlock `newsdoc:"meta,type=example/meta"`
Associates []exampleLink `newsdoc:"links,rel=associate"`
}
type exampleBlock struct {
Date *time.Time `newsdoc:"data.date,format=2006-01-02"`
Timestamp time.Time `newsdoc:"data.timestamp"`
Public bool `newsdoc:"data.public"`
}
type exampleLink struct {
Type string `newsdoc:"type"`
Name string `newsdoc:"name"`
Age *int `newsdoc:"data.age"`
}
func ExampleUnmarshalDocument() {
doc := newsdoc.Document{
UUID: "d04e9871-c3df-4fb0-878f-23f8d5ada7c2",
Meta: []newsdoc.Block{
{
Type: "example/meta",
Data: newsdoc.DataMap{
"date": "2023-08-13",
"timestamp": "2023-08-21T14:34:47+02:00",
"public": "true",
},
},
},
Links: []newsdoc.Block{
{
Rel: "associate",
Name: "Ren",
Type: "dog/chihuahua",
},
{
Rel: "associate",
Name: "Stimpy",
Type: "cat/manx",
Data: newsdoc.DataMap{"age": "3"},
},
},
}
var item exampleItem
err := darknut.UnmarshalDocument(doc, &item)
if err != nil {
panic(err)
}
fmt.Printf(`
UUID: %v
Date: %v
Timestamp: %v
Public: %v
`,
item.UUID, item.Meta.Date.Format(time.RFC3339),
item.Meta.Timestamp.Format(time.RFC3339), item.Meta.Public)
for _, a := range item.Associates {
fmt.Printf("* %s (%s)", a.Name, a.Type)
if a.Age != nil {
fmt.Printf(" age: %v", *a.Age)
}
fmt.Println()
}
// Output:
// UUID: d04e9871-c3df-4fb0-878f-23f8d5ada7c2
// Date: 2023-08-13T00:00:00Z
// Timestamp: 2023-08-21T14:34:47+02:00
// Public: true
//
// * Ren (dog/chihuahua)
// * Stimpy (cat/manx) age: 3
}