码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-09-26 21:36:01      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:团队   cmd.run   receive   max   list   sele   case   access   error   

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实现目录的监控过程

标签:团队   cmd.run   receive   max   list   sele   case   access   error   

原文地址:https://www.cnblogs.com/gpan/p/9709623.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!