DEV Community

manuel
manuel

Posted on • Originally published at mnlwldr.com on

1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay