initial commit
This commit is contained in:
commit
e607ebf747
7
go.mod
Normal file
7
go.mod
Normal 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
4
go.sum
Normal 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
BIN
notify.exe
Normal file
Binary file not shown.
77
notify.go
Normal file
77
notify.go
Normal 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
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user