diff --git a/os/gfsnotify/gfsnotify_watcher.go b/os/gfsnotify/gfsnotify_watcher.go index 80da7638d..d76d64483 100644 --- a/os/gfsnotify/gfsnotify_watcher.go +++ b/os/gfsnotify/gfsnotify_watcher.go @@ -106,11 +106,11 @@ func (w *Watcher) addWithCallbackFunc(name, path string, callbackFunc func(event // Close closes the watcher. func (w *Watcher) Close() { - w.events.Close() + close(w.closeChan) if err := w.watcher.Close(); err != nil { intlog.Errorf(context.TODO(), `%+v`, err) } - close(w.closeChan) + w.events.Close() } // Remove removes monitor and all callbacks associated with the `path` recursively. diff --git a/os/gfsnotify/gfsnotify_watcher_loop.go b/os/gfsnotify/gfsnotify_watcher_loop.go index cfd340c50..4ebca3ad8 100644 --- a/os/gfsnotify/gfsnotify_watcher_loop.go +++ b/os/gfsnotify/gfsnotify_watcher_loop.go @@ -8,6 +8,7 @@ package gfsnotify import ( "context" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" @@ -25,7 +26,10 @@ func (w *Watcher) watchLoop() { return // Event listening. - case ev := <-w.watcher.Events: + case ev, ok := <-w.watcher.Events: + if !ok { + return + } // Filter the repeated event in custom duration. _, err := w.cache.SetIfNotExist( context.Background(), diff --git a/os/gfsnotify/gfsnotify_z_unit_test.go b/os/gfsnotify/gfsnotify_z_unit_test.go index 0cab0a6b0..6155768e1 100644 --- a/os/gfsnotify/gfsnotify_z_unit_test.go +++ b/os/gfsnotify/gfsnotify_z_unit_test.go @@ -218,3 +218,23 @@ func TestWatcher_WatchFolderWithoutRecursively(t *testing.T) { t.Assert(array.Len(), 1) }) } + +func TestWatcher_WatchClose(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + var ( + err error + dirPath = gfile.Temp(gtime.TimestampNanoStr()) + watcher *gfsnotify.Watcher + ) + + err = gfile.Mkdir(dirPath) + t.AssertNil(err) + + watcher, err = gfsnotify.New() + t.AssertNil(err) + t.AssertNE(watcher, nil) + + time.Sleep(time.Millisecond * 100) + watcher.Close() + }) +}