Created
May 1, 2024 21:08
-
-
Save mpenick/11d264c649ed27cfc38449828371b1cc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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