siwm
siwm

Reputation: 189

Get Directory Disk Usage with Golang

I try to learn disk usage of directory with golang but this below app calculate incorrect. I do not want to use filepath.Walk. I tried os.Stat() but that did not get actual directory size. I shared related code statements below, correct directory information and results of app.

const (
    B  = 1
    KB = 1024 * B
    MB = 1024 * KB
    GB = 1024 * MB
)

type DiskStatus struct {
    All  uint64
    Free uint64
    Used uint64
}

func DiskUsage(path string) (ds DiskStatus) {
    fs := syscall.Statfs_t{}
    err := syscall.Statfs(path, &fs)
    if err != nil {
        return
    }
    ds.All = fs.Blocks * uint64(fs.Bsize)
    ds.Free = fs.Bfree * uint64(fs.Bsize)
    ds.Used = ds.All - ds.Free
    fmt.Println(path, ds.Used)
    return ds
}

func GetDir(destination_directory string) *[]model.Directory {
    var dir []model.Directory
    items, err := ioutil.ReadDir(destination_directory)

    if err != nil {
        log.Fatalln(err)
    }

    for _, item := range items {
        size := DiskUsage(destination_directory+item.Name()).Used / GB
        item := model.Directory{Path: item.Name(), TotalSize: size}
        dir = append(dir, item)
    }
    return &dir
}

Correct directory info:

$du -sh *
8.0K containers
2.0G testfolder
3.2M workspace

Results by App:

containers --> 90
testfolder --> 90
workspace --> 90

Upvotes: 1

Views: 1141

Answers (0)

Related Questions