-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
71 lines (57 loc) · 1.26 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
// Demonstrate the use of the viper package for configuration.
package main
import (
"fmt"
"log"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
type Config struct {
Server string
Port uint
}
func NewViper() *viper.Viper {
v := viper.New()
// Environment variables.
v.SetEnvPrefix("demo") // DEMO_
v.BindEnv("server") // DEMO_SERVER
v.BindEnv("port") // DEMO_PORT
v.SetDefault("server", "demo.example.com")
v.SetDefault("port", 8080)
// Config file.
// NOTE: Env vars take precedence!
// See precedence order: https://github.com/spf13/viper#why-viper
v.SetConfigName("config")
v.AddConfigPath(".")
v.AddConfigPath("/tmp")
return v
}
func main() {
v := NewViper()
if err := v.ReadInConfig(); err != nil {
log.Println(err)
}
var conf Config
if err := v.Unmarshal(&conf); err != nil {
log.Println(err)
}
// Print initial app settings.
fmt.Printf("%#v\n", &conf)
printConf(v)
// Watch config file and run callback function on changes.
v.WatchConfig()
v.OnConfigChange(func(e fsnotify.Event) {
if e.Op == fsnotify.Write {
printConf(v)
}
})
// Wait forever (exit with Ctrl-C).
select {}
}
func printConf(v *viper.Viper) {
log.Printf(
"server: %s, port: %d\n",
v.GetString("server"),
v.GetInt("port"),
)
}