码迷,mamicode.com
首页 > 其他好文 > 详细

go监视文件改变实现同步--包含遍历文件夹,执行cmd命令,检测文件改变

时间:2017-05-12 20:17:11      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:包含   defer   return   ref   scp   modify   str   als   .com   

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), "root@emb.mobi:/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命令,检测文件改变

标签:包含   defer   return   ref   scp   modify   str   als   .com   

原文地址:http://www.cnblogs.com/cdyboke/p/6846528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!