Skip to content

Commit 2273c89

Browse files
committed
Storage configuration implementation
1 parent 4390990 commit 2273c89

File tree

2 files changed

+48
-2
lines changed

2 files changed

+48
-2
lines changed

azure/storage/go.mod

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,7 @@ module blog-examples/azure/storage
22

33
go 1.13
44

5-
require github.com/fsnotify/fsnotify v1.4.9
5+
require (
6+
github.com/fsnotify/fsnotify v1.4.9
7+
github.com/spf13/viper v1.7.1
8+
)

azure/storage/liftbox.go

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,21 @@
11
package main
22

33
import (
4+
"flag"
45
"fmt"
56
"github.com/fsnotify/fsnotify"
7+
"github.com/spf13/viper"
68
"os"
79
"path/filepath"
810
)
911

12+
var configuration *viper.Viper
13+
14+
var (
15+
// flag name, default value in case the flag is not used and documentation
16+
flgConfigPath = flag.String("cfg", "./config.toml", "Path to configuration file")
17+
)
18+
1019
type Publisher interface {
1120
register(subscriber *Subscriber)
1221
unregister(subscriber *Subscriber)
@@ -86,9 +95,43 @@ func (pw *PathWatcher) observe() {
8695
<-done
8796
}
8897

98+
func bindEnvironmentVariables(conf *viper.Viper) {
99+
_ = conf.BindEnv("observer.rootpath", "ROOTPATH")
100+
}
101+
102+
func initConfiguration(conf *viper.Viper, filePath string) (*viper.Viper, error) {
103+
conf = viper.New()
104+
conf.SetConfigFile(filePath)
105+
106+
conf.WatchConfig()
107+
conf.OnConfigChange(func(e fsnotify.Event) {
108+
fmt.Printf("Config file changed: %v\n", e.Name)
109+
})
110+
111+
bindEnvironmentVariables(conf)
112+
113+
if err := conf.ReadInConfig(); err != nil {
114+
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
115+
return nil, err
116+
}
117+
118+
return nil, fmt.Errorf("config file was found but another error ocurred: %v", err)
119+
}
120+
121+
return conf, nil
122+
}
123+
89124
func main() {
125+
configuration, err := initConfiguration(configuration, *flgConfigPath)
126+
if err != nil {
127+
fmt.Printf("Error initializing configuration: %v", err)
128+
}
129+
130+
rootPath := configuration.GetString("observer.rootpath")
131+
fmt.Println(rootPath)
132+
90133
var pathWatcher Publisher = &PathWatcher{
91-
rootPath: "/home/username/liftbox",
134+
rootPath: rootPath,
92135
}
93136

94137
var pathIndexer Subscriber = &PathIndexer{}

0 commit comments

Comments
 (0)