How to Watch for File Changes in Go

Use the fsnotify package to create a watcher and listen for file system events on a specific path.

Use the fsnotify package to watch for file changes in Go. Install the package and create a new watcher, add the target path, then read events from the watcher's channel.

package main

import (
	"fmt"
	"log"

	"github.com/fsnotify/fsnotify"
)

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

	done := make(chan bool)
	go func() {
		for {
			select {
			case event, ok := <-watcher.Events:
				if !ok {
					return
				}
				fmt.Println("Event:", event)
			case err, ok := <-watcher.Errors:
				if !ok {
					return
				}
				log.Println("Error:", err)
			}
		}
	}()

	err = watcher.Add("/path/to/file")
	if err != nil {
		log.Fatal(err)
	}
	<-done
}