Skip to content

Instantly share code, notes, and snippets.

@mpenick
Created May 1, 2024 21:08
Show Gist options
  • Save mpenick/11d264c649ed27cfc38449828371b1cc to your computer and use it in GitHub Desktop.
Save mpenick/11d264c649ed27cfc38449828371b1cc to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"github.com/fsnotify/fsnotify"
"os"
"io"
)
func main() {
const configFile = "/test/test.txt"
w, err := fsnotify.NewWatcher()
if err != nil {
panic(err)
}
defer w.Close()
err = w.Add(configFile)
if err != nil {
panic(err)
}
for {
select {
case event, ok := <-w.Events:
if !ok {
return
}
if event.Op == fsnotify.Remove {
w.Remove(event.Name)
w.Add(configFile)
fmt.Println("Remove (reload)")
reload(configFile)
}
if event.Op&fsnotify.Write == fsnotify.Write {
fmt.Println("Write (reload)")
reload(configFile)
}
fmt.Println("event:", event)
case err, ok := <-w.Errors:
if !ok {
return
}
fmt.Println("error:", err)
}
}
}
func reload(name string) {
f, _ := os.Open(name)
defer f.Close()
buf, _ := io.ReadAll(f)
fmt.Println("content:", string(buf))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment