The [fsnotify]() is the most broadly used package for observing file changes. It supports multiple platforms and notification mechanisms:

  • inotify (Linux)
  • kqueue (BSD, MacOS, iOS)
  • ReadDirectoryChangesW (Windows)

Installation

go get -u golang.org/x/sys/...
go get -u github.com/fsnotify/fsnotify

Usage

The package itself is very minimalistic but provides the great benefit of observing file for changes. To get started, you have to initialize the watcher and register for monitoring the desired file path (can be file or directory):

watcher, err := fsnotify.NewWatcher()
if err != nil {
    log.Fatal(err)
}
defer watcher.Close()

You can register the files with the following function calls:

err = watcher.Add("/etc/daemon.cfg")
if err != nil {
   log.Fatal(err)
}

Finally, you have to create your own go routine that monitors the changes by reading the watcher.Events channel that got enqueued by any notification noticed by the watcher.

The event object provides an information about the file name and the change type (Create, Write, Remove, Rename or Chmod).

func monit() {
  for {
      select {
      case event := <-watcher.Events:
          log.Println("event:", event)
      case err := <-watcher.Errors:
          log.Println("error:", err)
      }
  }
}

go monit()

It’s very straight forward to build your service that can be reconfigure at any time and achive its high availability.