package main import ( "fmt" "os" ) func main() { srcDir := "/path/to/source" dstDir := "/path/to/destination" err := syncDirs(srcDir, dstDir) if err != nil { fmt.Println(err) } } func syncDirs(src, dst string) error { srcInfo, err := os.Stat(src) if err != nil { return err } if !srcInfo.IsDir() { return fmt.Errorf("%s is not a directory", src) } dstInfo, err := os.Stat(dst) if err != nil { return err } if !dstInfo.IsDir() { return fmt.Errorf("%s is not a directory", dst) } return filepath.Walk(src, func(path string, info os.FileInfo, err error) error { if err != nil { return err } relPath, err := filepath.Rel(src, path) if err != nil { return err } dstPath := filepath.Join(dst, relPath) if info.IsDir() { err := os.Mkdir(dstPath, 0777) if err != nil && !os.IsExist(err) { return err } } else { err := os.Link(path, dstPath) if err != nil { return err } } return nil }) }
package main import ( "fmt" "os" ) func main() { dir := "/path/to/directory" err := watchDir(dir) if err != nil { fmt.Println(err) } } func watchDir(dir string) error { watcher, err := fsnotify.NewWatcher() if err != nil { return err } defer watcher.Close() done := make(chan bool) go func() { for { select { case event := <-watcher.Events: if event.Op&fsnotify.Write == fsnotify.Write { fmt.Println("modified file:", event.Name) // perform action on file change } case err := <-watcher.Errors: fmt.Println("error:", err) } } }() err = watcher.Add(dir) if err != nil { return err } <-done return nil }In both examples, Go os File Sync is used in conjunction with other packages, such as os and filepath, to perform file and directory synchronization and monitoring.