使用golang实现目录的监控过程

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)
    }
}

转载于:https://www.cnblogs.com/gpan/p/9709623.html

你可能感兴趣的:(使用golang实现目录的监控过程)