歡迎光臨
每天分享高質量文章

GO實現檔案夾監控

收穫

  • 查看 watcher.go, 看出實現一個系統event的監控,代碼不過 625行;

  • 執行exec.Cmd(), cmd.Run(), 可以獲得shell的執行狀態;

  • 開始閱讀github上的開原始碼, 代碼特別精簡;

說明

專案組有一個需求,即當團隊人員更新Gitbook到服務器的時候,服務器的gitbook目錄下需要pull操作;

通過瞭解,當成員提交push內容到服務器的時候, git/objects目錄下內容會create, modify, access等事件;

前期通過shell+inotifywait實現,但是總存在push的時候獲取不到,或者上push之後頻繁更新gitbook;

本次使用 github.com/radovskyb/watcher 來使用;

其中在本地執行如下命令, 獲取watcher的庫;

go get github.com/radovskyb/watcher

通過範例,結合自己的腳本 pull.book.sh; 完成git book的操作;

package mainimport (    "fmt"
    "log"
    "os/exec"
    "time"

    "github.com/radovskyb/watcher")func main() {
    w := watcher.New()    // SetMaxEvents to 1 to allow at most 1 event's to be received
    // on the Event channel per watching cycle.
    //
    // If SetMaxEvents is not set, the default is to send all events.
    w.SetMaxEvents(1)    // Only notify rename and move events.
    //  w.FilterOps(watcher.Rename, watcher.Move)
    w.FilterOps(watcher.Create, watcher.Write, watcher.Chmod)    go func() {        for {            select {            case event := // Print the event's info.
                c := "pull.book.sh"
                cmd := exec.Command(c, "")
                err := cmd.Run()
                fmt.Printf("Command finished with error: %v\n", err)            case err := case return
            }
        }
    }()    // Watch this folder for changes.
    if err := w.Add("/srv/git/objects"); err != nil {
        log.Fatalln(err)
    }    // Watch test_folder recursively for changes.
    if err := w.AddRecursive("/srv/git/objects"); err != nil {
        log.Fatalln(err)
    }  /*
    // Print a list of all of the files and folders currently
    // being watched and their paths.
       for path, f := range w.WatchedFiles() {
         fmt.Printf("%s: %s\n", path, f.Name())
       }

       fmt.Println()
    */

    // Trigger 2 events after watcher started.
    go func() {
        w.Wait()
        w.TriggerEvent(watcher.Create, nil)
        w.TriggerEvent(watcher.Write, nil)
        w.TriggerEvent(watcher.Chmod, nil)
    }()    // Start the watching process - it'll check for changes every 100ms.
    if err := w.Start(time.Millisecond * 100); err != nil {
        log.Fatalln(err)
    }
}

赞(0)

分享創造快樂