使用golang實現目錄的監控過程
阿新 • • 發佈:2018-09-26
提交 開源代碼 select modify xevent ren efault shell 閱讀
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) } }
使用golang實現目錄的監控過程