-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
91 lines (77 loc) · 2.28 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
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
package main
import (
"fmt"
"os"
"reflect"
config "github.com/ThomasObenaus/go-conf"
"github.com/davecgh/go-spew/spew"
)
// LogLevel defines log levels.
type LogLevel int8
const (
// DebugLevel debug loglevel (contains messages of type debug, info, warn and error)
DebugLevel LogLevel = iota
// InfoLevel debug loglevel (contains messages of type info, warn and error)
InfoLevel
// WarnLevel debug loglevel (contains messages of type warn and error)
WarnLevel
// ErrorLevel debug loglevel (contains messages of type error)
ErrorLevel
)
type LogConfig struct {
Level LogLevel `cfg:"{'name':'level','desc':'Defines the loglevel (debug|info|warn|err).','default':'info','mapfun':'strToLogLevel'}"`
}
func main() {
args := []string{
"--level=err",
}
// 1. Create an instance of the config struct that should be filled
cfg := LogConfig{}
// 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. Register the mapping function
if err := provider.RegisterMappingFunc("strToLogLevel", strToLogLevel); err != nil {
panic(err)
}
// 4. Start reading and fill the config parameters
if err := provider.ReadConfig(args); 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)
}
// strToLogLevel maps a given string into a LogLevel (uint8)
func strToLogLevel(rawUntypedValue interface{}, targetType reflect.Type) (interface{}, error) {
// ensure that the expectation of the input type is satisfied
asStr, ok := rawUntypedValue.(string)
if !ok {
return nil, fmt.Errorf("Expected a string. Type '%T' is not supported", rawUntypedValue)
}
// return the target type
switch asStr {
case "debug":
return DebugLevel, nil
case "info":
return InfoLevel, nil
case "warn":
return WarnLevel, nil
case "err":
return ErrorLevel, nil
}
return nil, fmt.Errorf("%s is unknown", asStr)
}