Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Watch ¶
Watch watches the given filename and calls the given callback when the file is changed. The watcher uses the parent directory as a watchpoint to be notified if the file doesn't exist when the watcher is created. When the file is a symlink (like a ConfigMap or a Secret mounted in a Kubernetes Pod), a change of its target is detected as well. It relies on the events of the parent directory, which are all reported by inotify on Linux, but not always by kqueue (macOS, BSD). The file is watched until the end of the process. Use WatchWithContext to stop watching it. See ExampleWatch for an example.
Example ¶
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/perses/common/file"
)
func main() {
dir, err := os.MkdirTemp("", "watch")
if err != nil {
fmt.Println(err)
return
}
defer func() { _ = os.RemoveAll(dir) }()
filename := filepath.Join(dir, "test.txt")
changed := make(chan struct{}, 1)
err = file.Watch(filename, func() {
select {
case changed <- struct{}{}:
default:
}
})
if err != nil {
fmt.Println(err)
return
}
if err = os.WriteFile(filename, []byte("hello"), 0o600); err != nil {
fmt.Println(err)
return
}
<-changed
fmt.Println("File created or changed")
}
Output: File created or changed
func WatchWithContext ¶ added in v0.32.0
WatchWithContext is like Watch, but it stops watching the file once the context is done. The callback is not called anymore once the context is done, but a call in progress is not waited for.
Types ¶
This section is empty.