func srv DataMigrateService calculateDirectorySizedirPath string int64 error loggerInfofcalculate directory size startthe param is dirPaths dirPath var size int64 err = filepathWalkdirPath func_ stri
The calculateDirectorySize function is using the filepath.Walk function to traverse the directory and calculate the total size of all regular files within it. However, during the traversal, it encounters a file or directory that does not exist, resulting in the "no such file or directory" error.
This error can occur if the directory being scanned contains symbolic links or if there are permission issues preventing access to certain files or directories.
To resolve this issue, you can add error handling to skip over files or directories that cannot be accessed or do not exist. Here's an updated version of the function that handles such errors:
func (srv *DataMigrateService) calculateDirectorySize(dirPath string) (int64, error) {
logger.Infof("calculate directory size start...,the param is dirPath:%s", dirPath)
var size int64
err := filepath.Walk(dirPath, func(_ string, info os.FileInfo, err error) error {
if err != nil {
logger.Error(err.Error())
// Skip over files or directories that cannot be accessed
if os.IsNotExist(err) || os.IsPermission(err) {
return nil
}
return err
}
if !info.Mode().IsRegular() {
return nil
}
size += info.Size()
return nil
})
if err != nil {
logger.Error(err.Error())
return 0, err
}
return size, nil
}
With this updated code, any "no such file or directory" errors will be skipped, and the function will continue calculating the size of the remaining files.
原文地址: http://www.cveoy.top/t/topic/ij6s 著作权归作者所有。请勿转载和采集!