One thing you could do would be to define a channel inside of DirSizeMB
, and define readSize
inside of that function so it gets the channel as a closure. Then send all of the sizes out the channel and sum them as you receive them.
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
Why use a channel?
Unless you've read the underlying code, you don't actually know how filepath.Walk
invokes your readSize function. While it probably calls it sequentially over all of the files on the given path, the implementation could theoretically invoke several of these calls simultaneously on separate goroutines (the docs would probably mention this if it did). In any case, in a language designed for concurrency, it's good practice to make sure that your code is safe.
The answer that @DaveC gives shows how to do this by using a closure over a local variable solves the problem of having a global variable, so multiple simultaneous calls to DirSize would be safe. The Docs for Walk explicitly state that the walk function runs over files in a deterministic order, so his solution is sufficient for this problem, but I'll leave this as an example of how to make it safe to run the inner function concurrently.