-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.go
83 lines (77 loc) · 2.41 KB
/
example.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
// package main in the example can be used to demo the settings
// parsing from command line, environment variables, specified
// override files and environment overrides. A few example commands
// to try:
//
// For an environment override (partial settings override)
// $ GO_ENV=example go run examples/example.go
//
// For a argument provided file override (partial settings override)
// $ go run examples/example.go --config-file examples/config-override.yml
//
// For an environment override (partial settings override) with additional
// env var settings
// $ GO_ENV=example LISTS_ANIMALS=cat,dog,bear,hare go run examples/example.go
//
// Try mixing and matching ENV VAR and command line arguments to observe the
// order of priority
// $ GO_ENV=example DATA_PORT=27019 go run examples/example.go --data-port 27018
package main
import (
"fmt"
"log"
"go.jtlabs.io/settings"
)
// this is a silly struct for storing config / settings
// with example fields for demonstration purposes
type config struct {
Data struct {
Name string `yaml:"name"`
Host string `yaml:"host"`
Port int `yaml:"port"`
} `yaml:"data"`
Logging struct {
Level string `yaml:"level"`
Verbose bool `yaml:"verbose"`
} `yaml:"logging"`
Name string `yaml:"name"`
Server struct {
Address string `yaml:"address"`
} `yaml:"server"`
Version string `yaml:"version"`
Lists struct {
LuckyNumbers []int `yaml:"luckyNumbers"`
Animals []string `yaml:"animals"`
} `yaml:"lists"`
}
func main() {
var c config
options := settings.Options().
SetBasePath("./examples/defaults.yaml").
SetDefaultsMap(map[string]interface{}{
"Server.Address": ":8080",
}).
SetEnvOverride("GO_ENV").
SetEnvSearchPaths("./examples", "./", "./config", "./settings").
SetArgsFileOverride("--config-file", "-cf").
SetArgsMap(map[string]string{
"--data-name": "Data.Name",
"--data-host": "Data.Host",
"--data-port": "Data.Port",
"--lists-animals": "Lists.Animals",
"--lists-lucky-numbers": "Lists.LuckyNumbers",
"--logging-verbose": "Logging.Verbose",
}).
SetVarsMap(map[string]string{
"DATA_NAME": "Data.Name",
"DATA_HOST": "Data.Host",
"DATA_PORT": "Data.Port",
"SERVER_ADDRESS": "Server.Address",
"LISTS_ANIMALS": "Lists.Animals",
})
// read in configuration from all sources
if err := settings.Gather(options, &c); err != nil {
log.Fatal(err)
}
fmt.Println(c)
}