-
Notifications
You must be signed in to change notification settings - Fork 7
/
config.go
52 lines (45 loc) · 1.04 KB
/
config.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
package app
import (
"encoding/json"
"os"
"github.com/omeid/uconfig"
"github.com/omeid/uconfig/plugins/file"
"github.com/rs/zerolog/log"
)
// ConfigFilename is the filename of the config file automatically loaded by SetupConfig
var ConfigFilename = "config.json"
// SetupConfig loads the configuration in the given struct. In case of error, prints help and exit application.
func SetupConfig(config interface{}) {
var files uconfig.Files
if fileExists(ConfigFilename) {
files = []struct {
Path string
Unmarshal file.Unmarshal
}{
{
Path: ConfigFilename,
Unmarshal: json.Unmarshal,
},
}
}
c, err := uconfig.Classic(config, files)
if err != nil {
if c != nil {
c.Usage()
}
if isErrHelpRequested(err) {
os.Exit(0)
}
log.Fatal().Err(err).Msg("Failed to setup config")
}
}
func isErrHelpRequested(err error) bool {
return err != nil && err.Error() == "flag: help requested"
}
func fileExists(path string) bool {
stat, err := os.Stat(path)
if err != nil {
return false
}
return !stat.IsDir()
}