summaryrefslogtreecommitdiff
path: root/playground/main.go
blob: 8487c5bd91b27d2fcf12f9d4709e46fa4d8fce22 (plain)
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
package main

import (
	"encoding/json"
	"fmt"
	"html/template"
	"log"
	"os"
)

type Optional[T any] struct {
	Value  T
	Exists bool
}

func (o *Optional[T]) UnmarshalJSON(data []byte) error {
	var Temp *T

	err := json.Unmarshal(data, &Temp)
	if err != nil {
		return err
	}

	if Temp == nil {
		var empty T
		o.Value = empty
		o.Exists = false
		return nil
	}

	o.Value = *Temp
	o.Exists = true
	return nil
}

func (o Optional[T]) MarshalJSON() ([]byte, error) {
	var Temp *T

	if o.Exists {
		Temp = &o.Value
	}

	return json.Marshal(Temp)
}

type Testy struct {
	Flag *bool            `json:"flag"`
	Cake *[]string        `json:"cake"`
	Opt  Optional[string] `json:"opt"`
}

const TEXT = `{
	"cake": [
		"one",
		"two",
		"three"
	],
	"opt": "peter"
}`

const TEMPLATE = `Flag is: {{if .Flag}}{{.Flag}}{{else}}[none]{{end}}
Cake is: {{if .Cake}}{{range .Cake}}{{.}} {{end}}{{else}}[none]{{end}}
Opt is: {{if .Opt.Exists}}{{.Opt.Value}}{{else}}[none]{{end}}
`

func main() {
	var t Testy
	json.Unmarshal([]byte(TEXT), &t)

	tmpl, err := template.New("mytemplate").Parse(TEMPLATE)
	if err != nil {
		log.Fatal(err)
	}

	tmpl.Execute(os.Stdout, t)

	b, err := json.Marshal(t)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(b))
}