This repository was archived by the owner on Aug 22, 2019. It is now read-only.
forked from JeremyLoy/config
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_test.go
112 lines (87 loc) · 2.24 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
// NOTE: os.Clearenv must be called before each test that uses env vars to avoid false positives with env bleeding over.
package config_test
import (
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/hookactions/config"
)
type MySubConfig struct {
IPWhitelist []string
}
type MyConfig struct {
DatabaseURL string `config:"DATABASE_URL"`
Port int
FeatureFlag bool `config:"FEATURE_FLAG"`
SubConfig MySubConfig
}
func Example() {
os.Clearenv()
os.Setenv("DATABASE_URL", "db://")
os.Setenv("PORT", "1234")
os.Setenv("FEATURE_FLAG", "true") // also accepts t, f, 0, 1 etc. see strconv package.
// Double underscore for sub structs. Space separation for slices.
os.Setenv("SUBCONFIG__IPWHITELIST", "0.0.0.0 1.1.1.1 2.2.2.2")
var c MyConfig
config.FromEnv().To(&c)
fmt.Println(c.DatabaseURL)
fmt.Println(c.Port)
fmt.Println(c.FeatureFlag)
fmt.Println(c.SubConfig.IPWhitelist, len(c.SubConfig.IPWhitelist))
// Output:
// db://
// 1234
// true
// [0.0.0.0 1.1.1.1 2.2.2.2] 3
}
func Example_fromFileWithOverride() {
tempFile, _ := ioutil.TempFile("", "temp")
tempFile.Write([]byte(strings.Join([]string{"PORT=1234", "FEATURE_FLAG=true"}, "\n")))
tempFile.Close()
os.Clearenv()
os.Setenv("DATABASE_URL", "db://")
os.Setenv("PORT", "5678")
var c MyConfig
config.From(tempFile.Name()).FromEnv().To(&c)
// db:// was only set in ENV
fmt.Println(c.DatabaseURL)
// 1234 was overridden by 5678
fmt.Println(c.Port)
// FeatureFlag was was only set in file
fmt.Println(c.FeatureFlag)
// Output:
// db://
// 5678
// true
}
func Example_structTags() {
type MyConfig struct {
// NOTE: even when using tags, lookup is still case insensitive.
// dAtABase_urL would still work.
DatabaseURL string `config:"DATABASE_URL"`
}
os.Clearenv()
os.Setenv("DATABASE_URL", "db://")
var c MyConfig
config.FromEnv().To(&c)
fmt.Println(c.DatabaseURL)
// Output:
// db://
}
type MyPreProcessor struct{}
func (p *MyPreProcessor) PreProcessValue(key, value string) string {
return strings.ToUpper(value)
}
func ExampleWithValuePreProcessor() {
type MyConfig struct {
Foo string
}
os.Clearenv()
os.Setenv("FOO", "bar")
var c MyConfig
config.WithValuePreProcessor(&MyPreProcessor{}).FromEnv().To(&c)
fmt.Println(c.Foo)
// Output:
// BAR
}