-
Notifications
You must be signed in to change notification settings - Fork 9
/
marshal_example_test.go
66 lines (52 loc) · 1.52 KB
/
marshal_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
package jsonapi_test
import (
"fmt"
"github.com/DataDog/jsonapi"
)
func ExampleMarshal() {
type Article struct {
ID string `jsonapi:"primary,articles"`
Title string `jsonapi:"attribute" json:"title"`
}
a := Article{ID: "1", Title: "Hello World"}
b, err := jsonapi.Marshal(&a)
if err != nil {
panic(err)
}
fmt.Printf("%s", string(b))
// Output: {"data":{"id":"1","type":"articles","attributes":{"title":"Hello World"}}}
}
func ExampleMarshal_slice() {
type Article struct {
ID string `jsonapi:"primary,articles"`
Title string `jsonapi:"attribute" json:"title"`
}
a := []*Article{
{ID: "1", Title: "Hello World"},
{ID: "2", Title: "Hello Again"},
}
b, err := jsonapi.Marshal(&a)
if err != nil {
panic(err)
}
fmt.Printf("%s", string(b))
// Output: {"data":[{"id":"1","type":"articles","attributes":{"title":"Hello World"}},{"id":"2","type":"articles","attributes":{"title":"Hello Again"}}]}
}
func ExampleMarshal_meta() {
type ArticleMeta struct {
Views int `json:"views"`
}
type Article struct {
ID string `jsonapi:"primary,articles"`
Title string `jsonapi:"attribute" json:"title"`
Meta *ArticleMeta `jsonapi:"meta"`
}
a := Article{ID: "1", Title: "Hello World", Meta: &ArticleMeta{Views: 10}}
m := map[string]any{"foo": "bar"}
b, err := jsonapi.Marshal(&a, jsonapi.MarshalMeta(m))
if err != nil {
panic(err)
}
fmt.Printf("%s", string(b))
// Output: {"data":{"id":"1","type":"articles","attributes":{"title":"Hello World"},"meta":{"views":10}},"meta":{"foo":"bar"}}
}