DEV Community

manuel
manuel

Posted on • Originally published at mnlwldr.com on

Filewatcher in Golang

#go

This is a simple example of how to move files from one folder to another automatically with Go and 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
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)