Add WatchConfigWithError and remove the log.Fatal in WatchConfig

This commit is contained in:
dreamans 2022-04-10 18:23:29 +08:00
parent 9a8603d8f8
commit 214fba280a
2 changed files with 28 additions and 3 deletions

View file

@ -428,19 +428,30 @@ func (v *Viper) OnConfigChange(run func(in fsnotify.Event)) {
func WatchConfig() { v.WatchConfig() }
func (v *Viper) WatchConfigWithError() <-chan error{
return v.watchConfig()
}
func (v *Viper) WatchConfig() {
v.watchConfig()
}
func (v *Viper) watchConfig() <-chan error {
initWG := sync.WaitGroup{}
initWG.Add(1)
errChan := make(chan error, 1)
go func() {
watcher, err := newWatcher()
if err != nil {
log.Fatal(err)
errChan <- err
initWG.Done()
return
}
defer watcher.Close()
// we have to watch the entire directory to pick up renames/atomic saves in a cross-platform way
filename, err := v.getConfigFile()
if err != nil {
log.Printf("error: %v\n", err)
errChan <- err
initWG.Done()
return
}
@ -483,7 +494,7 @@ func (v *Viper) WatchConfig() {
case err, ok := <-watcher.Errors:
if ok { // 'Errors' channel is not closed
log.Printf("watcher error: %v\n", err)
errChan <- err
}
eventsWG.Done()
return
@ -495,6 +506,7 @@ func (v *Viper) WatchConfig() {
eventsWG.Wait() // now, wait for event loop to end in this go-routine...
}()
initWG.Wait() // make sure that the go routine above fully ended before returning
return errChan
}
// SetConfigFile explicitly defines the path, name and extension of the config file.

View file

@ -2369,6 +2369,19 @@ func newViperWithSymlinkedConfigFile(t *testing.T) (*Viper, string, string, func
return v, watchDir, configFile, cleanup
}
func TestWatchFileWithError(t *testing.T) {
t.Run("config file not found", func(t *testing.T) {
errChan := v.WatchConfigWithError()
err := <-errChan
require.Error(t, err)
})
//TODO: newWatcher error
t.Run("newWatcher an error occurred", func(t *testing.T) {
})
}
func TestWatchFile(t *testing.T) {
if runtime.GOOS == "linux" {
// TODO(bep) FIX ME