Files
  • main.go
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"time"
)

func notCustom() {
	// :show start
	type Event struct {
		What string
		When time.Time
	}
	e := Event{
		What: "earthquake",
		When: time.Now(),
	}
	d, err := json.Marshal(&e)
	if err != nil {
		log.Fatalf("json.MarshalIndent failed with '%s'\n", err)
	}
	fmt.Printf("Standard time JSON: %s\n", string(d))
	// :show end
}

// :show start
type customTime time.Time

const customTimeFormat = `"2006-02-01"`

func (ct customTime) MarshalJSON() ([]byte, error) {
	t := time.Time(ct)
	s := t.Format(customTimeFormat)
	return []byte(s), nil
}

func (ct *customTime) UnmarshalJSON(d []byte) error {
	t, err := time.Parse(customTimeFormat, string(d))
	if err != nil {
		return err
	}
	*ct = customTime(t)
	return nil
}

type Event2 struct {
	What string
	When customTime
}

// :show end

func custom() {
	// :show start
	e := Event2{
		What: "earthquake",
		When: customTime(time.Now()),
	}
	d, err := json.Marshal(&e)
	if err != nil {
		log.Fatalf("json.Marshal failed with '%s'\n", err)
	}
	fmt.Printf("\nCustom time JSON: %s\n", string(d))
	var decoded Event2
	err = json.Unmarshal(d, &decoded)
	if err != nil {
		log.Fatalf("json.Unmarshal failed with '%s'\n", err)
	}
	t := time.Time(decoded.When)
	fmt.Printf("Decoded custom time: %s\n", t.Format(customTimeFormat))
	// :show end
}

func main() {
	// :show start
	notCustom()
	custom()
	// :show end
}
go version go1.9.4 linux/amd64