Documentation
¶
Overview ¶
Package watcher provides a simple, thread-safe, polling-based filesystem watcher.
It allows you to monitor files and directories for changes (Create, Write, Remove) recursively. The watcher operates by periodically scanning the watched paths for modifications, making it a reliable choice across different platforms where native filesystem event notifications might be inconsistent.
Features:
- Watches directories recursively and can also watch individual files.
- Thread-safe: paths can be added or removed from the watchlist from multiple goroutines.
- Simple event system using a channel.
Basic Usage Snippet ¶
The following snippet demonstrates how to create a watcher, add a path, and listen for events within your application.
// Create a new watcher. A 200ms poll interval is a reasonable default.
w := watcher.New(200 * time.Millisecond)
defer w.Close() // Ensure the watcher is closed gracefully on shutdown.
// Start a background goroutine to handle events.
go func() {
for event := range w.Events {
// When w.Close() is called, the Events channel will be closed,
// and this for...range loop will exit.
fmt.Println(event) // e.g., "Event{Path: "/path/to/file.txt", Op: WRITE}"
}
}()
// Add a path to watch. This can be a directory or a single file.
// This call is thread-safe, so you can call it from other goroutines as well.
if err := w.Watch("/path/to/your/directory"); err != nil {
log.Fatalln(err)
}
// Your main application logic continues here...
// The watcher will run in the background.
// To stop the watcher and its background goroutine, simply call w.Close().
Package watcher provides a simple, thread-safe, polling-based filesystem watcher.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Event ¶
type Event struct {
Path string // The absolute path to the file or directory that changed.
Op Op // The operation that occurred.
}
Event represents a single filesystem change.
type Op ¶
type Op uint32
Op represents the type of filesystem operation detected by the watcher.
type Watcher ¶
type Watcher struct {
// Events is the channel where filesystem change notifications are sent.
Events chan Event
// contains filtered or unexported fields
}
Watcher scans registered paths for file changes and sends events.
func New ¶
New creates a new Watcher instance and starts its background scanning goroutine. pollInterval specifies how often to scan for changes. To prevent excessive CPU usage, a minimum interval of 100ms is enforced.