1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-12-18 08:26:38 +02:00
go-micro/config/source/file/watcher_linux.go
Mohamed MHAMDI ad8fca255b
fix(config): fix file source watcher stop behavior when Stop is called (#2630)
Co-authored-by: Mohamed MHAMDI <mmhamdi@hubside.com>
2023-04-26 02:19:52 +02:00

72 lines
1.2 KiB
Go

//go:build linux
// +build linux
package file
import (
"os"
"github.com/fsnotify/fsnotify"
"go-micro.dev/v4/config/source"
)
type watcher struct {
f *file
fw *fsnotify.Watcher
}
func newWatcher(f *file) (source.Watcher, error) {
fw, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
fw.Add(f.path)
return &watcher{
f: f,
fw: fw,
}, nil
}
func (w *watcher) Next() (*source.ChangeSet, error) {
// try get the event
select {
case event, ok := <-w.fw.Events:
// check if channel was closed (i.e. Watcher.Close() was called).
if !ok {
return nil, source.ErrWatcherStopped
}
if event.Has(fsnotify.Rename) {
// check existence of file, and add watch again
_, err := os.Stat(event.Name)
if err == nil || os.IsExist(err) {
w.fw.Add(event.Name)
}
}
c, err := w.f.Read()
if err != nil {
return nil, err
}
// add path again for the event bug of fsnotify
w.fw.Add(w.f.path)
return c, nil
case err, ok := <-w.fw.Errors:
// check if channel was closed (i.e. Watcher.Close() was called).
if !ok {
return nil, source.ErrWatcherStopped
}
return nil, err
}
}
func (w *watcher) Stop() error {
return w.fw.Close()
}