go监视文件改变实现同步--包含遍历文件夹,执行cmd命令,检测文件改变
Posted dy blog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go监视文件改变实现同步--包含遍历文件夹,执行cmd命令,检测文件改变相关的知识,希望对你有一定的参考价值。
package main import ( "fmt" "time" "os/exec" "strings" "io/ioutil" "os" "github.com/howeyc/fsnotify" ) const filePath = "/home/ubuntu/GzhuOJ/public" var watcher *fsnotify.Watcher func Print(args ...interface{}) { fmt.Println(time.Now(), args) } func isDir(path string) bool { fileInfo, err := os.Stat(path) if err != nil { Print("error:", err.Error()) return false } return fileInfo.IsDir() } func watchPath(filePath string) { Print("watchPath:", filePath) err := watcher.Watch(filePath) if err != nil { Print(err.Error()) return } } func broweDir(path string) { Print("broweDir:", path) dir, err := os.Open(path) if err != nil { Print("error:", err.Error()) return } defer dir.Close() names, err := dir.Readdirnames(-1) if err != nil { Print("error:", err.Error()) return } for _, name := range names { dirPath := path + "/" + name if !isDir(dirPath) { continue } watchPath(dirPath) broweDir(dirPath) } } func main() { var err error watcher, err = fsnotify.NewWatcher() if err != nil { panic(err) } defer watcher.Close() broweDir(filePath) watchPath(filePath) dealWatch() } func dealWatch() { for { select { case event := <-watcher.Event: Print("event: ", event) if !event.IsModify() && !event.IsCreate() { break } cmd := exec.Command("scp", "-r", "-P 23456", filePath+strings.TrimPrefix(event.Name, filePath), "[email protected]:/home/public") Print("cmd:", cmd.Args) stderr, err := cmd.StderrPipe() if err != nil { Print(err.Error()) break } stdout, err := cmd.StdoutPipe() if err != nil { Print(err.Error()) break } if err = cmd.Start(); err != nil { Print(err.Error()) break } errBytes, err := ioutil.ReadAll(stderr) if err != nil { Print(err.Error()) break } outBytes, err := ioutil.ReadAll(stdout) if err != nil { Print(err.Error()) break } if len(errBytes) != 0 { Print("errors:", string(errBytes)) } if len(outBytes) != 0 { Print("output:", string(outBytes)) } case err := <-watcher.Error: Print("error: ", err.Error()) } } }
要注意的是一个fsnotify.Watcher能watch多个文件和文件夹
以上是关于go监视文件改变实现同步--包含遍历文件夹,执行cmd命令,检测文件改变的主要内容,如果未能解决你的问题,请参考以下文章