So I am trying to get total size of a directory using Go. So far I have this:
var dirSize int64 = 0
func readSize(path string, file os.FileInfo, err error) error {
if !file.IsDir() {
dirSize += file.Size()
}
return nil
}
func DirSizeMB(path string) float64 {
dirSize = 0
filepath.Walk(path, readSize)
sizeMB := float64(dirSize) / 1024.0 / 1024.0
sizeMB = Round(sizeMB, .5, 2)
return sizeMB
}
The question is whether the dirSize
global variable is going to cause problems and if it does, how do I move it to the scope of the DirSizeMB
function?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With