fix: fsnotify watcher panics when closing (#3399)

This commit is contained in:
gopherfarm
2024-04-07 14:12:03 +08:00
committed by GitHub
parent 83ba887df7
commit 505fc25a64
3 changed files with 27 additions and 3 deletions

View File

@ -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.

View File

@ -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(),

View File

@ -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()
})
}