, , - DirSizeMB readSize , . .
func DirSizeMB(path string) float64 {
sizes := make(chan int64)
readSize := func(path string, file os.FileInfo, err error) error {
if err != nil || file == nil {
return nil // Ignore errors
}
if !file.IsDir() {
sizes <- file.Size()
}
return nil
}
go func() {
filepath.Walk(path, readSize)
close(sizes)
}()
size := int64(0)
for s := range sizes {
size += s
}
sizeMB := float64(size) / 1024.0 / 1024.0
sizeMB = Round(sizeMB, 0.5, 2)
return sizeMB
}
http://play.golang.org/p/zzKZu0cm9n
?
, , filepath.Walk readSize. , , , goroutines (, , , ). , , concurrency, , .
The answer @DaveC gives shows how to do this, using closure on a local variable, solves the problem of having a global variable, so multiple simultaneous calls to DirSize would be safe. Docs for Walk explicitly states that the walk function works on files in a deterministic order, so its solution is enough for this problem, but I will leave this as an example of how to make it safe to execute an internal function at the same time.
source
share