-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
60 lines (51 loc) · 1.4 KB
/
main.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
package main
import (
"fmt"
"os"
"time"
config "github.com/ThomasObenaus/go-conf"
"github.com/davecgh/go-spew/spew"
)
// PrimitiveTypes Define the config struct and annotate it with the cfg tag.
type PrimitiveTypes struct {
Field1 string `cfg:"{'name':'field-1'}"`
Field2 int `cfg:"{'name':'field-2'}"`
Field3 float64 `cfg:"{'name':'field-3'}"`
Field4 bool `cfg:"{'name':'field-4'}"`
Field5 time.Duration `cfg:"{'name':'field-5'}"`
}
func main() {
args := []string{
"--field-1=one",
"--field-2=1234",
"--field-3=12.34",
"--field-4=true",
"--field-5=1234m",
}
// 1. Create an instance of the config struct that should be filled
cfg := PrimitiveTypes{}
// 2. Create an instance of the config provider which is responsible to read the config
// from defaults, environment variables, config file or command line
prefixForEnvironmentVariables := "MY_APP"
nameOfTheConfig := "MY_APP"
provider, err := config.NewConfigProvider(
&cfg,
nameOfTheConfig,
prefixForEnvironmentVariables,
)
if err != nil {
panic(err)
}
// 3. Start reading and fill the config parameters
err = provider.ReadConfig(args)
if err != nil {
fmt.Println("##### Failed reading the config")
fmt.Printf("Error: %s\n", err.Error())
fmt.Println("Usage:")
fmt.Print(provider.Usage())
os.Exit(1)
}
fmt.Println("##### Successfully read the config")
fmt.Println()
spew.Dump(cfg)
}