How to Use Filesystem Notifications in Go (fsnotify)

Use fsnotify to watch directories for file changes and handle events via a channel.

Use github.com/fsnotify/fsnotify to create a watcher, add a path, and read events from a channel.

package main

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
)

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

	err = watcher.Add("/path/to/dir")
	if err != nil {
		panic(err)
	}

	for {
		select {
		case event, ok := <-watcher.Events:
			if !ok {
				return
			}
			fmt.Println("Event:", event)
		case err, ok := <-watcher.Errors:
			if !ok {
				return
			}
			fmt.Println("Error:", err)
		}
	}
}