How do I watch file changes in Go?

In Go, you can watch for file changes using the `fsnotify` package. This package provides a simple way to monitor file system events, such as modifications, creations, deletions, and renaming of files and directories. Below is a code example demonstrating how to use `fsnotify` to watch for changes in a specific file or directory.

package main import ( "fmt" "log" "github.com/fsnotify/fsnotify" ) func main() { // Create a new file watcher watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } defer watcher.Close() // Start listening for events go func() { for { select { case event, ok := <-watcher.Events: if !ok { return } fmt.Println("event:", event) if event.Op&fsnotify.Write == fsnotify.Write { fmt.Println("modified file:", event.Name) } case err, ok := <-watcher.Errors: if !ok { return } log.Println("error:", err) } } }() // Add a specific file or directory to watch err = watcher.Add("/path/to/your/file/or/directory") if err != nil { log.Fatal(err) } // Block forever <-make(chan struct{}) }

Go file system watcher fsnotify file changes