This commit is contained in:
2024-06-22 05:13:30 +00:00
parent 8e449f25a8
commit 193b121893
4 changed files with 164 additions and 0 deletions

View File

@@ -0,0 +1,54 @@
package main
import (
"context"
"log"
"os"
"os/signal"
"github.com/fsnotify/fsnotify"
)
func main() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
ctx, cancel := context.WithCancel(context.Background())
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
log.Println("event:", event)
if event.Has(fsnotify.Create) {
log.Println("created file:", event.Name)
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
case <-ctx.Done():
return
}
}
}()
if err = watcher.Add("/home/yono/watchdir"); err != nil {
log.Fatal(err)
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
cancel()
}

7
fsnotify-demo/go.mod Normal file
View File

@@ -0,0 +1,7 @@
module fsnotify-demo
go 1.22.4
require github.com/fsnotify/fsnotify v1.7.0
require golang.org/x/sys v0.4.0 // indirect

4
fsnotify-demo/go.sum Normal file
View File

@@ -0,0 +1,4 @@
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18=
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=