Skip to content

Instantly share code, notes, and snippets.

@lalizita
Created March 31, 2023 14:52
Show Gist options
  • Save lalizita/60ef67d85a6fc64f20d7c09ab92c781d to your computer and use it in GitHub Desktop.
Save lalizita/60ef67d85a6fc64f20d7c09ab92c781d to your computer and use it in GitHub Desktop.
Example that shows a channel cant be read more than one time
func main() {
fileUpdated := make(chan string)
go WatchEvents(fileUpdated)
var filename string
go func() {
for range fileUpdated {
filename = <-fileUpdated
fmt.Println("File updated:", filename)
}
}()
//While is sleeping edit the text file
time.Sleep(4 * time.Second)
fmt.Println("OUT OF FOR:", filename)
}
func WatchEvents(updateF chan<- string) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
path, _ := os.Getwd()
filep := fmt.Sprintf("%s/text/text.txt", path)
err = watcher.Add(filep)
if err != nil {
log.Fatal(err)
}
if err != nil {
log.Fatal("Error in file path:", err.Error())
}
for event := range watcher.Events {
if event.Has(fsnotify.Write) {
updateF <- event.Name
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment