gfsnotify

gfsnotify能监控指定文件的修改情况,如文件的增加、删除、修改、重命名等操作。

使用方式:

  1. import "gitee.com/johng/gf/g/os/gfsnotify"

方法列表:godoc.org/github.com/johng-cn/gf/g/os/gfsnotify

  1. func Add(path string, callback func(event *Event)) error
  2. func Remove(path string) error
  3. type Event
  4. func (e *Event) IsChmod() bool
  5. func (e *Event) IsCreate() bool
  6. func (e *Event) IsRemove() bool
  7. func (e *Event) IsRename() bool
  8. func (e *Event) IsWrite() bool
  9. type Watcher
  10. func New() (*Watcher, error)
  11. func (w *Watcher) Add(path string, callback func(event *Event)) error
  12. func (w *Watcher) Close()
  13. func (w *Watcher) Remove(path string) error

gfsnotify模块提供了直接的AddRemove模块方法,用于添加监控和取消监控。此外也可能通过New方法创建一个监控管理对象之后再进行监控管理。其中,添加监控的时候需要给定触发监控时的回调函数,参数为*gfsnotify.Event对象指针。

使用示例:

  1. package main
  2. import (
  3. "log"
  4. "gitee.com/johng/gf/g/os/gfsnotify"
  5. )
  6. func main() {
  7. err := gfsnotify.Add("/home/john/Documents/temp", func(event *gfsnotify.Event) {
  8. if event.IsCreate() {
  9. log.Println("创建文件 : ", event.Path)
  10. }
  11. if event.IsWrite() {
  12. log.Println("写入文件 : ", event.Path)
  13. }
  14. if event.IsRemove() {
  15. log.Println("删除文件 : ", event.Path)
  16. }
  17. if event.IsRename() {
  18. log.Println("重命名文件 : ", event.Path)
  19. }
  20. if event.IsChmod() {
  21. log.Println("修改权限 : ", event.Path)
  22. }
  23. })
  24. if err != nil {
  25. log.Fatalln(err)
  26. } else {
  27. select {}
  28. }
  29. }

当我们修改/home/john/Documents/temp文件时,可以看到gfsnotify监控到了文件的修改并输出了对应的事件信息。