代码
package zdpgo_fileimport ("errors""os""path/filepath""strings"
)
func CopyDir(srcPath, desPath string) error {if !IsDir(srcPath) {return errors.New("要复制的文件夹不存在")}if strings.TrimSpace(srcPath) == strings.TrimSpace(desPath) {return errors.New("源文件夹和目标文件夹不能相同")}if !IsDir(desPath) {err := AddDir(desPath)if err != nil {return err}}srcPath = strings.Replace(srcPath, "\\", "/", -1)desPath = strings.Replace(desPath, "\\", "/", -1)err := filepath.Walk(srcPath, func(path string, f os.FileInfo, err error) error {if f == nil {return err}if path == srcPath {return nil}destNewPath := desPath + "/" + pathdestNewPath = strings.Replace(destNewPath, "\\", "/", -1)if strings.Count(destNewPath, desPath) > 1 {return nil}if !f.IsDir() {err = CopyFile(path, destNewPath)if err != nil {return err}} else {if !IsExist(destNewPath) {return AddDir(destNewPath)}}return nil})return err
}
测试
package zdpgo_fileimport "testing"func TestCopyDir(t *testing.T) {if err := AddDir("test"); err != nil {t.Fatal(err)}data := []struct {Src stringDst string}{{".", "test/test2"},{"test/test2", "test/test1"},}for _, tt := range data {v := CopyDir(tt.Src, tt.Dst)if v != nil {t.Error(v)}}
}
测试结果