-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
95 lines (74 loc) · 1.96 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
package config_test
import (
"fmt"
"os"
"github.com/krostar/config"
sourceenv "github.com/krostar/config/source/env"
)
type Config struct {
NoDefault string
Some OtherConfig
SomeOther *OtherConfig
SomeLast *OtherConfig
}
type OtherConfig struct {
UniversalAnswer int
}
func (c *OtherConfig) SetDefault() {
c.UniversalAnswer = 42
}
func ExampleLoad() {
var cfg Config
os.Setenv("MYAPP_SOMEOTHER_UNIVERSALANSWER", "1010") // nolint: errcheck, gosec
defer os.Unsetenv("MYAPP_SOMEOTHER_UNIVERSALANSWER") // nolint: errcheck, gosec
if err := config.Load(&cfg, config.WithSources(
sourceenv.New("myapp"),
)); err != nil {
panic(err)
}
fmt.Printf("cfg.NoDefault = %q\n", cfg.NoDefault)
fmt.Printf("cfg.Some.UniversalAnswer = %d\n", cfg.Some.UniversalAnswer)
fmt.Printf("cfg.SomeOther.UniversalAnswer = %d\n", cfg.SomeOther.UniversalAnswer)
fmt.Printf("cfg.SomeLast = %v\n", cfg.SomeLast)
// Output:
// cfg.NoDefault = ""
// cfg.Some.UniversalAnswer = 42
// cfg.SomeOther.UniversalAnswer = 1010
// cfg.SomeLast = <nil>
}
type HTTPConfig struct {
Debug bool
ListenAddress string
}
func (c *HTTPConfig) SetDefault() {
c.ListenAddress = "127.0.0.1:8080"
}
func (c HTTPConfig) Validate() error {
if c.ListenAddress == "" {
return fmt.Errorf("listening address can't be empty")
}
return nil
}
func ExampleValidate() {
cfg := HTTPConfig{
Debug: false,
ListenAddress: "",
}
err := config.Validate(&cfg)
fmt.Println("failed:", err != nil)
fmt.Println("reason:", err.Error())
// Output:
// failed: true
// reason: validation error: listening address can't be empty
}
func ExampleSetDefault() {
var cfg HTTPConfig
if err := config.SetDefault(&cfg); err != nil {
panic("unable to set defaults")
}
fmt.Println("debug:", cfg.Debug)
fmt.Println("listen-address:", cfg.ListenAddress)
// Output:
// debug: false
// listen-address: 127.0.0.1:8080
}