package main import ( "log" "github.com/go-fsnotify/fsnotify" ) func main() { watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } defer watcher.Close() done := make(chan bool) go func() { for { select { case event := <-watcher.Events: log.Println("event:", event) if event.Op&fsnotify.Write == fsnotify.Write { log.Println("modified file:", event.Name) } case err := <-watcher.Errors: log.Println("error:", err) } } }() err = watcher.Add("slog") if err != nil { log.Fatal(err) } <-done }
package main import ( "github.com/howeyc/fsnotify" "log" ) type monitor struct { watch *fsnotify.Watcher } func main() { M, err := NewMonitor() if err != nil { log.Println(err) return } M.Do() M.watch.Watch("../") select {} } func NewMonitor() (monitor, error) { Mon, err := fsnotify.NewWatcher() return monitor{Mon}, err } func (self monitor) Do() { go func() { for { select { case w := <-self.watch.Event: log.Println(w) if w.IsModify() { continue } if w.IsDelete() { log.Println("文件被删除.") continue } if w.IsRename() { w = <-self.watch.Event log.Println(w) self.watch.RemoveWatch(w.Name) log.Println(w.Name, " 被重命名.") } case err := <-self.watch.Error: log.Fatalln(err) } } }() }
版权声明:本文为博主原创文章,未经博主允许不得转载。
有疑问加站长微信联系(非本文作者)