GO實現資料夾監控

jjwsed發表於2018-09-26

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 main

import (
    "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 := <-w.Event:
                fmt.Println(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 := <-w.Error:
                log.Fatalln(err)
            case <-w.Closed:
                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)
    }
}

更多原創文章乾貨分享,請關注公眾號
  • GO實現資料夾監控
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章