File: examples_test.go

package info (click to toggle)
golang-github-bep-tmc 0.5.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 108 kB
  • sloc: makefile: 2
file content (72 lines) | stat: -rw-r--r-- 1,278 bytes parent folder | download
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
// Copyright © 2019 Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.

package tmc_test

import (
	"fmt"
	"log"

	"github.com/bep/tmc"
	yaml "gopkg.in/yaml.v2"
)

func Example() {
	m1 := map[string]interface{}{"num": 42}
	c, err := tmc.New()
	if err != nil {
		log.Fatal(err)
	}

	data, err := c.Marshal(m1)
	if err != nil {
		log.Fatal(err)
	}

	m2 := make(map[string]interface{})
	err = c.Unmarshal(data, &m2)
	if err != nil {
		log.Fatal(err)
	}
	num := m2["num"]

	fmt.Printf("%v (%T)", num, num)
	// Output: 42 (int)

}

func ExampleWithMarshalUnmarshaler() {
	m1 := map[string]interface{}{"num": 42}
	c, err := tmc.New(tmc.WithMarshalUnmarshaler(new(yamlMarshaler)))
	if err != nil {
		log.Fatal(err)
	}

	data, err := c.Marshal(m1)
	if err != nil {
		log.Fatal(err)
	}

	m2 := make(map[string]interface{})
	err = c.Unmarshal(data, &m2)
	if err != nil {
		log.Fatal(err)
	}
	num := m2["num"]

	fmt.Printf("%v (%T)", num, num)
	// Output: 42 (int)
}

type yamlMarshaler int

func (yamlMarshaler) Marshal(v interface{}) ([]byte, error) {
	return yaml.Marshal(v)

}

func (yamlMarshaler) Unmarshal(b []byte, v interface{}) error {
	return yaml.Unmarshal(b, v)
}