Created
March 31, 2023 14:52
-
-
Save lalizita/60ef67d85a6fc64f20d7c09ab92c781d to your computer and use it in GitHub Desktop.
Example that shows a channel cant be read more than one time
This file contains 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
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