-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathViperExMPLE.go
78 lines (65 loc) · 1.77 KB
/
ViperExMPLE.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
package main
import (
"bytes"
"fmt"
"github.com/spf13/viper"
"io/ioutil"
"os"
"path"
"time"
)
func main() {
viper.AutomaticEnv()
for k, v := range viper.AllSettings() {
fmt.Println(k, v)
}
fmt.Println(time.Now().Truncate(time.Second))
dir, _ := os.Getwd()
fmt.Println(dir)
configBytes, err := ioutil.ReadFile(path.Join(dir, "devconfig.yaml"))
if err != nil {
fmt.Println(fmt.Errorf("IGNORING this Error when reading config: %v\n", err))
}
v1, err := readConfig("config", map[string]interface{}{
"server.port": 8800,
})
if err != nil {
panic(fmt.Errorf("Error when reading config: %v\n", err))
}
fmt.Println(len(configBytes))
err = v1.MergeConfig(bytes.NewBuffer(configBytes)) // Find and read the config file
if err != nil { // Handle errors reading the config file
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
port := v1.GetInt("server.port")
hostname := v1.GetString("hostname")
auth := v1.GetStringMapString("auth")
fmt.Printf("Reading config for port = %d\n", port)
fmt.Printf("Reading config for hostname = %s\n", hostname)
fmt.Printf("Reading config for auth = %#v\n", auth)
}
func readConfig(filename string, defaults map[string]interface{}) (*viper.Viper, error) {
v := viper.New()
v.SetConfigName(filename)
v.AddConfigPath(".")
v.AutomaticEnv()
err := v.ReadInConfig()
for key, value := range defaults {
v.Set(key, value)
}
return v, err
}
/*func init() {
// Set viper path and read configuration
if os.Getenv("ENV") == "PRODUCTION" {
viper.AddConfigPath("config")
} else {
viper.AddConfigPath("devconfig")
}
viper.AddConfigPath(".")
err := viper.ReadInConfig()
// Handle errors reading the config file
if err != nil {
log.Fatalln("Fatal error config file", err)
}
}*/