Skip to content

Instantly share code, notes, and snippets.

@sdomino
Last active August 25, 2022 08:37
Show Gist options
  • Save sdomino/74980d69f9fa80cb9d73 to your computer and use it in GitHub Desktop.
Save sdomino/74980d69f9fa80cb9d73 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/go-fsnotify/fsnotify"
)
//
var watcher *fsnotify.Watcher
// main
func main() {
// creates a new file watcher
watcher, _ = fsnotify.NewWatcher()
defer watcher.Close()
// starting at the root of the project, walk each file/directory searching for
// directories
if err := filepath.Walk("/Users/skdomino/Desktop/test", watchDir); err != nil {
fmt.Println("ERROR", err)
}
//
done := make(chan bool)
//
go func() {
for {
select {
// watch for events
case event := <-watcher.Events:
fmt.Printf("EVENT! %#v\n", event)
// watch for errors
case err := <-watcher.Errors:
fmt.Println("ERROR", err)
}
}
}()
<-done
}
// watchDir gets run as a walk func, searching for directories to add watchers to
func watchDir(path string, fi os.FileInfo, err error) error {
// since fsnotify can watch all the files in a directory, watchers only need
// to be added to each nested directory
if fi.Mode().IsDir() {
return watcher.Add(path)
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment