diff --git a/config/provider.go b/config/provider.go index 8bf81cf..132bddf 100644 --- a/config/provider.go +++ b/config/provider.go @@ -34,11 +34,16 @@ func (p *FilesystemProvider) Watch(ctx context.Context, fp string) (<-chan Event ch := make(chan Event) go func() { - defer watcher.Close() + defer func() { + watcher.Close() + close(ch) + }() + for { select { case ev, ok := <-watcher.Events: if !ok { + fmt.Println("watch error: wather.Events closed") return } if ev.Op&fsnotify.Write == 0 { @@ -54,7 +59,10 @@ func (p *FilesystemProvider) Watch(ctx context.Context, fp string) (<-chan Event return } fmt.Println("watch error:", err) - close(ch) + return + case <-ctx.Done(): + fmt.Println("watch cancelled") + return } } }() diff --git a/config/provider_test.go b/config/provider_test.go index 7dee7ee..683e4bc 100644 --- a/config/provider_test.go +++ b/config/provider_test.go @@ -5,6 +5,7 @@ import ( "os" "path/filepath" "testing" + "time" ) var fsProvider = &FilesystemProvider{} @@ -32,16 +33,29 @@ func TestFilesystemProvider_Watch(t *testing.T) { fp := filepath.Join(d, "testdata/change.ini") - ch, err := fsProvider.Watch(context.TODO(), fp) + ctx, cancel := context.WithCancel(context.TODO()) + ch, err := fsProvider.Watch(ctx, fp) if err != nil { t.Fatalf("watch error: %v", err) } + go func() { + defer cancel() + + os.WriteFile(fp, []byte("helloworld0"), 0666) + time.Sleep(time.Second) + os.WriteFile(fp, []byte("helloworld1"), 0666) + time.Sleep(time.Second) + os.WriteFile(fp, []byte("helloworld2"), 0666) + time.Sleep(time.Second) + }() + +LOOP: for { select { case ev, ok := <-ch: if !ok { - break + break LOOP } t.Logf("load ok: %s", ev.meta) default: diff --git a/config/testdata/change.ini b/config/testdata/change.ini index d40f128..75b0c00 100644 --- a/config/testdata/change.ini +++ b/config/testdata/change.ini @@ -1,21 +1 @@ -# possible values : production, development -app_mode = development - -[paths] -# Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used) -data = /home/git/grafana - -[server] -# Protocol (http or https) -protocol = http - -# The http port to use -http_port = 9999 - -# Redirect to correct domain if host header does not match domain -# Prevents DNS rebinding attacks -enforce_domain = true - -hello = 1 -hellox = 2 -helloz = 4 \ No newline at end of file +helloworld2 \ No newline at end of file