forked from ardanlabs/gotraining
/
main.go
67 lines (55 loc) · 1.37 KB
/
main.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
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// Sample program to show how to implement the json.Marshaler interface
// to dictate the marshaling.
package main
import (
"encoding/json"
"log"
"os"
"time"
)
// User represents a user in the system.
type User struct {
FirstName string
LastName string
Age int
CreatedAt time.Time
Admin bool
Bio *string
}
// MarshalJSON implements the json.Marshaler interface so we
// can dictate how the user is marshaled.
func (u *User) MarshalJSON() ([]byte, error) {
// Create a document of key/value pairs for each field.
m := map[string]interface{}{
"first_name": u.FirstName,
"CreatedAt": u.CreatedAt,
"Admin": u.Admin,
"Bio": u.Bio,
}
// Omit the last name from the document unless
// we have a value.
if u.LastName != "" {
m["LastName"] = u.LastName
}
// We always omit Age so nothing to do.
return json.Marshal(m)
}
func main() {
// Encode a zero valued version of a user and write to stdout.
err := json.NewEncoder(os.Stdout).Encode(&User{})
if err != nil {
log.Fatal(err)
}
// Create a user value for Mary Jane.
u := User{
FirstName: "Mary",
LastName: "Jane",
}
// Encode the user value and write to stdout.
err = json.NewEncoder(os.Stdout).Encode(&u)
if err != nil {
log.Fatal(err)
}
}