Golang 通过fsnotify监控文件,检测文件夹目录层级文件夹变化,菜鸟一枚,欢迎赐教!
1. 调用fsnotify包监控文件:
FSNotify.go
package FSNotify
import (
"fmt"
"github.com/fsnotify/fsnotify"
"os"
"path/filepath"
)
type NotifyFile struct {
watch *fsnotify.Watcher
}
func NewNotifyFile() *NotifyFile {
w := new(NotifyFile)
w.watch, _ = fsnotify.NewWatcher()
return w
}
//监控目录
func (this *NotifyFile) WatchDir(dir string) {
//通过Walk来遍历目录下的所有子目录
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
//判断是否为目录,监控目录,目录下文件也在监控范围内,不需要加
if info.IsDir() {
path, err := filepath.Abs(path)
if err != nil {
return err
}
err = this.watch.Add(path)
if err != nil {
return err
}
fmt.Println("监控 : ", path)
}
return nil
})
go this.WatchEv