Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get directory total size?

Tags:

go

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?

like image 251
zola Avatar asked Sep 09 '15 14:09

zola


1 Answers

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.

like image 79
Dave C Avatar answered Nov 15 '22 19:11

Dave C