-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
123 lines (102 loc) · 1.99 KB
/
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package cfg_test
import (
"bytes"
"fmt"
"github.com/walle/cfg"
)
func ExampleMarshal() {
type MyConfig struct {
Answer int
Pi float64
IsActive bool `cfg:"is_active"`
Quotes string `cfg:"quotes"`
unexported string
NotUsed string `cfg:"-"`
}
var myConfig = &MyConfig{
Answer: 42,
Pi: 3.14,
IsActive: true,
Quotes: "Alea iacta est\nEt tu, Brute?",
unexported: "foo",
NotUsed: "bar",
}
data, err := cfg.Marshal(myConfig)
if err != nil {
// Handle error
}
fmt.Printf("%s", data)
// Output:
// Answer = 42
// Pi = 3.14
// is_active = true
// quotes = Alea iacta est\nEt tu, Brute?
}
func ExampleUnmarshal() {
type MyConfig struct {
Answer int
Pi float64
IsActive bool `cfg:"is_active"`
Quotes string `cfg:"quotes"`
unexported string
NotUsed string `cfg:"-"`
}
const configString = `
# This is a comment
# An integer value
answer = 42
# A float value
pi = 3.14
# A boolean value
is_active = true
# A string value
quotes = Alea iacta est\nEt tu, Brute?
`
myConfig := &MyConfig{}
err := cfg.Unmarshal([]byte(configString), myConfig)
if err != nil {
// Handle error
}
fmt.Println(myConfig.Answer)
fmt.Println(myConfig.Pi)
fmt.Println(myConfig.IsActive)
fmt.Println(myConfig.Quotes)
// Output:
// 42
// 3.14
// true
// Alea iacta est
// Et tu, Brute?
}
func ExampleNewConfigFromReader() {
const configString = `
# This is a comment
# An integer value
answer = 42
# A float value
pi = 3.14
# A boolean value
is_active = true
# A string value
quotes = Alea iacta est\nEt tu, Brute?
`
r := bytes.NewBufferString(configString)
config, err := cfg.NewConfigFromReader(r)
if err != nil {
// Handle error
}
a, _ := config.GetInt("answer")
fmt.Println(a)
p, _ := config.GetFloat("pi")
fmt.Println(p)
i, _ := config.GetBool("is_active")
fmt.Println(i)
q, _ := config.GetString("quotes")
fmt.Println(q)
// Output:
// 42
// 3.14
// true
// Alea iacta est
// Et tu, Brute?
}