« Back

Filewatcher in Golang

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
}