Add Watch

  1. package main
  2. import (
  3. "context"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/os/gfsnotify"
  6. )
  7. func main() {
  8. var (
  9. path = "/home/john/temp"
  10. ctx = context.Background()
  11. logger = g.Log()
  12. callback = func(event *gfsnotify.Event) {
  13. if event.IsCreate() {
  14. logger.Debug(ctx, "Create file: ", event.Path)
  15. }
  16. if event.IsWrite() {
  17. logger.Debug(ctx, "Write file: ", event.Path)
  18. }
  19. if event.IsRemove() {
  20. logger.Debug(ctx, "Delete file: ", event.Path)
  21. }
  22. if event.IsRename() {
  23. logger.Debug(ctx, "Rename file: ", event.Path)
  24. }
  25. if event.IsChmod() {
  26. logger.Debug(ctx, "Change permissions: ", event.Path)
  27. }
  28. logger.Debug(ctx, event)
  29. }
  30. )
  31. _, err := gfsnotify.Add(path, callback, gfsnotify.WatchOption{})
  32. if err != nil {
  33. logger.Fatal(ctx, err)
  34. } else {
  35. select {}
  36. }
  37. }

The /home/john parameter is a directory. When we create/delete/modify files in the /home/john directory, gfsnotify detects the file modifications and outputs the corresponding event information.

Recursive Watching

We can use gfsnotify.WatchOption to set some options for watching, such as whether to enable recursive watching. By default, the Add method performs recursive watching, meaning that changes to files within the directory (including those in subdirectories) will also trigger the file watching callback.

If we create new directories under the watched directory and continue to create new directories or files within them, and so on, the newly created directories or files will also be automatically watched.