-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_yaml_test.go
64 lines (55 loc) · 1.18 KB
/
example_yaml_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
package cfg_test
import (
"context"
"fmt"
"time"
"github.com/zpatrick/cfg"
"gopkg.in/yaml.v3"
)
type MyConfig struct {
Timeout time.Duration
ServerPort int
ServerAddr string
}
type yamlFile struct {
Timeout *time.Duration `yaml:"timeout"`
Server struct {
Port *int `yaml:"port"`
Addr *string `yaml:"addr"`
} `yaml:"server"`
}
func ExampleYAML() {
const data = `
timeout: 5s
server:
port: 8080
`
var f yamlFile
if err := yaml.Unmarshal([]byte(data), &f); err != nil {
panic(err)
}
var c MyConfig
if err := cfg.Load(context.Background(), cfg.Schemas{
"timeout": cfg.Schema[time.Duration]{
Dest: &c.Timeout,
Provider: cfg.StaticProviderAddr(f.Timeout, false),
},
"server.port": cfg.Schema[int]{
Dest: &c.ServerPort,
Provider: cfg.StaticProviderAddr(f.Server.Port, false),
},
"server.addr": cfg.Schema[string]{
Dest: &c.ServerAddr,
Default: cfg.Addr("localhost"),
Provider: cfg.StaticProviderAddr(f.Server.Addr, false),
},
}); err != nil {
panic(err)
}
fmt.Printf("Timeout: %s ServerPort: %d ServerAddr: %s",
c.Timeout,
c.ServerPort,
c.ServerAddr,
)
// Output: Timeout: 5s ServerPort: 8080 ServerAddr: localhost
}