目錄監控

package main

import (
   "log"

   "github.com/fsnotify/fsnotify"
)

func main() {
   watcher, err := fsnotify.NewWatcher()
   if err != nil {
      log.Fatal(err)
   }
   defer watcher.Close()

   done := make(chan bool)
   go func() {
      for {
         select {
         case event, ok := <-watcher.Events:
            if !ok {
               return
            }
            switch event {
               case "CREATE":
                  fmt.Printf("The file:%v created.", event.Name)
            }
            if event.Op&fsnotify.Write == fsnotify.Write {
               log.Println("modified file:", event.Name)
            }
         case err, ok := <-watcher.Errors:         
            if !ok {
               return
            }
            log.Println("error:", err)
         }
      }
   }()

   err = watcher.Add("/root/dirmonitor/xdir")
   if err != nil {
      log.Fatal(err)
   }
   <-done
}