1. 程式人生 > >go語言之監控資料夾

go語言之監控資料夾

//在執行檔案中 
// conf
//  |--app.conf
//   monitor.exe
//  app.conf中的內容
//  command="ls -l"
//  monitordir ="c:\\test"
//  在windows下會執行兩次
// https://github.com/howeyc/fsnotify/issues/106


package main

import (
    "fmt"
    "github.com/astaxie/beego"
    "gopkg.in/fsnotify.v1"
    "os/exec"
    "strings"
)

func mkcmd(command string) error {
    argArray := strings.Split(command, " ")
    cmd := exec.Command(argArray[0], argArray[1:]...)
    buff, err := cmd.Output()
    fmt.Println(string(buff))

    if err != nil {

        return err
    }
    return nil
}

func main() {
    command := beego.AppConfig.String("command")
    monitordir := beego.AppConfig.String("monitordir")
    fmt.Printf("command=%s, monitordir=%s\n", command, monitordir)

    watcher, err := fsnotify.NewWatcher()
    if err != nil {
        fmt.Println(err)
    }
    defer watcher.Close()

    done := make(chan bool)

    // Process events
    go func() {
        for {
            select {
            case ev := <-watcher.Events:
                //do something
                if ev.Op&fsnotify.Write == fsnotify.Write {
                    err := mkcmd(command)
                    if err != nil {
                        fmt.Println(err)
                    }
                }
            case err := <-watcher.Errors:
                fmt.Println(err)
            }
        }
    }()

    err = watcher.Add(monitordir)
    if err != nil {
        fmt.Println(err)

    }

    <-done
    watcher.Close()
}