|
1 | 1 | package main
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "flag" |
4 | 5 | "fmt"
|
5 | 6 | "github.com/fsnotify/fsnotify"
|
| 7 | + "github.com/spf13/viper" |
6 | 8 | "os"
|
7 | 9 | "path/filepath"
|
8 | 10 | )
|
9 | 11 |
|
| 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 | + |
10 | 19 | type Publisher interface {
|
11 | 20 | register(subscriber *Subscriber)
|
12 | 21 | unregister(subscriber *Subscriber)
|
@@ -86,9 +95,43 @@ func (pw *PathWatcher) observe() {
|
86 | 95 | <-done
|
87 | 96 | }
|
88 | 97 |
|
| 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 | + |
89 | 124 | 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 | + |
90 | 133 | var pathWatcher Publisher = &PathWatcher{
|
91 |
| - rootPath: "/home/username/liftbox", |
| 134 | + rootPath: rootPath, |
92 | 135 | }
|
93 | 136 |
|
94 | 137 | var pathIndexer Subscriber = &PathIndexer{}
|
|
0 commit comments