-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
84 lines (65 loc) · 1.76 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
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
package goMartialConfig
import (
"fmt"
"log"
"os"
"strings"
"github.com/Masterminds/semver"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
func init() {
viper.SetDefault("config.filename", "config")
viper.SetDefault("config.format", "yaml")
}
func SetAppVersion(verStr string) {
var appVersion *semver.Version
var err error
appVersion, err = semver.NewVersion(verStr)
if err != nil {
log.Fatalln("Error setting app version")
}
viper.SetDefault("app.version", appVersion)
}
func SetAppName(appName, appPrefix string) {
viper.SetDefault("app.name", appName)
viper.SetDefault("app.prefix", appPrefix)
}
func GetConfigs() {
var helpRequested bool
var versionRequested bool
viper.SetConfigName(viper.GetString("config.filename"))
viper.SetConfigType(viper.GetString("config.format"))
viper.AddConfigPath(fmt.Sprintf("/etc/%s/", viper.GetString("app.prefix")))
viper.AddConfigPath(fmt.Sprintf("$HOME/.%s/", viper.GetString("app.prefix")))
viper.AddConfigPath("./etc/")
viper.WatchConfig()
viper.SetEnvPrefix(viper.GetString("app.prefix"))
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv()
pflag.BoolVarP(&helpRequested, "help", "h", false, "This message")
pflag.BoolVarP(&versionRequested, "version", "v", false, "Get Program Version")
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
} else {
log.Fatal("invalid config file format")
}
}
pflag.Parse()
_ = viper.BindPFlags(pflag.CommandLine)
if helpRequested {
showHelp()
}
if versionRequested {
showVersion()
}
}
func showHelp() {
fmt.Printf("Usage: %s:\n", os.Args[0])
pflag.PrintDefaults()
os.Exit(0)
}
func showVersion() {
fmt.Printf("%s: %s\n", os.Args[0], viper.Get("app.version"))
os.Exit(0)
}