How to get directory total size?
Using a global like that at best is bad practice.
It's also a race if DirSizeMB
is called concurrently.
The simple solution is to use a closure, e.g.:
func DirSize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
size += info.Size()
}
return err
})
return size, err
}
Playground
You could assign the closure to a variable if you think that looks better.