me

notes from mnlwldr

Thoughts about programming and other things I want to share

@mnlwldr on Twitter @mnlwldr on GitHub @mnlwldr on Mastodon mnlwldr@gmail.com defer.cc

I wrote a little tool in Golang to move files from directory ‘a’ to ‘b’ I had a task today where, among other things, I had to keep moving files from one folder to another. After doing it 5 times, I wanted to automate it with fsnotify/fsnotify.

func main() {
	srcDir := "path/to/a"
	destDir := "path/to/b"

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer watcher.Close()

	done := make(chan bool)
	go func() {
		for {

			event, ok := <-watcher.Events
			if !ok {
				return
			}
			if event.Op.String() == "CREATE" {
				log.Println("[event] ", event)
				newPath := destDir + filepath.Base(event.Name)
				err := os.Rename(event.Name, newPath)
				if err != nil {
					log.Fatal(err)
				}
			}
		}
	}()
	err = watcher.Add(srcDir)
	if err != nil {
		log.Fatal(err)
	}
	<-done
}
Tags: #golang

Have you written a response to this? Let me know the URL