Last active
August 25, 2022 08:37
-
-
Save sdomino/74980d69f9fa80cb9d73 to your computer and use it in GitHub Desktop.
How to detect file changes in Golang: https://medium.com/@skdomino/watch-this-file-watching-in-go-5b5a247cf71f
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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