gitee.com/sasukebo/go-micro/v4@v4.7.1/config/source/file/watcher.go (about) 1 //go:build !linux 2 // +build !linux 3 4 package file 5 6 import ( 7 "os" 8 9 "gitee.com/sasukebo/go-micro/v4/config/source" 10 "github.com/fsnotify/fsnotify" 11 ) 12 13 type watcher struct { 14 f *file 15 16 fw *fsnotify.Watcher 17 exit chan bool 18 } 19 20 func newWatcher(f *file) (source.Watcher, error) { 21 fw, err := fsnotify.NewWatcher() 22 if err != nil { 23 return nil, err 24 } 25 26 fw.Add(f.path) 27 28 return &watcher{ 29 f: f, 30 fw: fw, 31 exit: make(chan bool), 32 }, nil 33 } 34 35 func (w *watcher) Next() (*source.ChangeSet, error) { 36 // is it closed? 37 select { 38 case <-w.exit: 39 return nil, source.ErrWatcherStopped 40 default: 41 } 42 43 // try get the event 44 select { 45 case event, _ := <-w.fw.Events: 46 if event.Op == fsnotify.Rename { 47 // check existence of file, and add watch again 48 _, err := os.Stat(event.Name) 49 if err == nil || os.IsExist(err) { 50 w.fw.Add(event.Name) 51 } 52 } 53 54 c, err := w.f.Read() 55 if err != nil { 56 return nil, err 57 } 58 return c, nil 59 case err := <-w.fw.Errors: 60 return nil, err 61 case <-w.exit: 62 return nil, source.ErrWatcherStopped 63 } 64 } 65 66 func (w *watcher) Stop() error { 67 return w.fw.Close() 68 }