initial commit

This commit is contained in:
Suyono 2024-06-23 12:34:22 +10:00
commit e607ebf747
6 changed files with 90 additions and 0 deletions

0
LICENSE Normal file
View File

2
README.md Normal file
View File

@ -0,0 +1,2 @@
# inotify-demo

7
go.mod Normal file
View File

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

4
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=

BIN
notify.exe Normal file

Binary file not shown.

77
notify.go Normal file
View File

@ -0,0 +1,77 @@
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"github.com/fsnotify/fsnotify"
)
func main() {
var (
watcher *fsnotify.Watcher
err error
dir2Watch string
)
if dir2Watch, err = checkArgs(); err != nil {
log.Fatal("Error:", err)
}
if watcher, err = fsnotify.NewWatcher(); err != nil {
log.Fatal("Error:", err)
}
defer watcher.Close()
ctx, cancel := context.WithCancel(context.Background())
go watcherFunc(ctx, watcher)
if err = watcher.Add(dir2Watch); err != nil {
log.Fatal("Error:", err)
}
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt)
fmt.Println("watching the directory, press ctrl-c to stop...")
<-done
cancel()
fmt.Println()
fmt.Println("ended")
}
func watcherFunc(ctx context.Context, watcher *fsnotify.Watcher) {
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
}
}
}
func checkArgs() (string, error) {
if len(os.Args) != 2 {
return "", fmt.Errorf("invalid arguments")
}
return "", nil
}