-
Notifications
You must be signed in to change notification settings - Fork 12
/
jsonViper.go
72 lines (60 loc) · 1.38 KB
/
jsonViper.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
package main
import (
"encoding/json"
"fmt"
"os"
"github.com/spf13/viper"
)
type ConfigStructure struct {
MacPass string `mapstructure:"macos"`
LinuxPass string `mapstructure:"linux"`
WindowsPass string `mapstructure:"windows"`
PostHost string `mapstructure:"postgres"`
MySQLHost string `mapstructure:"mysql"`
MongoHost string `mapstructure:"mongodb"`
}
func PrettyPrint(v interface{}) (err error) {
b, err := json.MarshalIndent(v, "", " ")
if err == nil {
fmt.Println(string(b))
}
return
}
var CONFIG = ".config.json"
func main() {
if len(os.Args) == 1 {
fmt.Println("Using default file", CONFIG)
} else {
CONFIG = os.Args[1]
}
viper.SetConfigType("json")
viper.SetConfigFile(CONFIG)
fmt.Printf("Using config: %s\n", viper.ConfigFileUsed())
viper.ReadInConfig()
if viper.IsSet("macos") {
fmt.Println("macos:", viper.Get("macos"))
} else {
fmt.Println("macos not set!")
}
if viper.IsSet("active") {
value := viper.GetBool("active")
if value {
postgres := viper.Get("postgres")
mysql := viper.Get("mysql")
mongo := viper.Get("mongodb")
fmt.Println("P:", postgres, "My:", mysql, "Mo:", mongo)
}
} else {
fmt.Println("active is not set!")
}
if !viper.IsSet("DoesNotExist") {
fmt.Println("DoesNotExist is not set!")
}
var t ConfigStructure
err := viper.Unmarshal(&t)
if err != nil {
fmt.Println(err)
return
}
PrettyPrint(t)
}