Rick Smith
Rick Smith

Reputation: 9251

Get amount of free disk space using Go

Basically I want the output of df -h, which includes both the free space and the total size of the volume. The solution needs to work on Windows, Linux, and Mac and be written in Go.

I have looked through the os and syscall Go documentation and haven't found anything. On Windows, even command line utils are either awkward (dir C:\) or need elevated privileges (fsutil volume diskfree C:\). Surely there is a way to do this that I haven't found yet...

UPDATE:
Per nemo's answer and invitation, I have provided a cross-platform Go package that does this.

Upvotes: 49

Views: 36110

Answers (3)

nemo
nemo

Reputation: 57659

On POSIX systems you can use sys.unix.Statfs.
Example of printing free space in bytes of current working directory:

import "golang.org/x/sys/unix"
import "os"

var stat unix.Statfs_t

wd, err := os.Getwd()

unix.Statfs(wd, &stat)

// Available blocks * size per block = available space in bytes
fmt.Println(stat.Bavail * uint64(stat.Bsize))

For Windows you need to go the syscall route as well. Example (source, updated to match new sys/windows package):

import "golang.org/x/sys/windows"

var freeBytesAvailable uint64
var totalNumberOfBytes uint64
var totalNumberOfFreeBytes uint64

err := windows.GetDiskFreeSpaceEx(windows.StringToUTF16Ptr("C:"),
    &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes)

Feel free to write a package that provides the functionality cross-platform. On how to implement something cross-platform, see the build tool help page.

Upvotes: 78

Roman Shishkin
Roman Shishkin

Reputation: 2605

Here is my version of the df -h command based on github.com/shirou/gopsutil library

package main

import (
    "fmt"

    human "github.com/dustin/go-humanize"
    "github.com/shirou/gopsutil/disk"
)

func main() {
    formatter := "%-14s %7s %7s %7s %4s %s\n"
    fmt.Printf(formatter, "Filesystem", "Size", "Used", "Avail", "Use%", "Mounted on")

    parts, _ := disk.Partitions(true)
    for _, p := range parts {
        device := p.Mountpoint
        s, _ := disk.Usage(device)

        if s.Total == 0 {
            continue
        }

        percent := fmt.Sprintf("%2.f%%", s.UsedPercent)

        fmt.Printf(formatter,
            s.Fstype,
            human.Bytes(s.Total),
            human.Bytes(s.Used),
            human.Bytes(s.Free),
            percent,
            p.Mountpoint,
        )
    }
}

Upvotes: 11

Iain McLaren
Iain McLaren

Reputation: 99

Minio has a package (GoDoc) to show disk usage that is cross platform, and seems to be well maintained:

import (
        "github.com/minio/minio/pkg/disk"
        humanize "github.com/dustin/go-humanize"
)

func printUsage(path string) error {
        di, err := disk.GetInfo(path)
        if err != nil {
            return err
        }
        percentage := (float64(di.Total-di.Free)/float64(di.Total))*100
        fmt.Printf("%s of %s disk space used (%0.2f%%)\n", 
            humanize.Bytes(di.Total-di.Free), 
            humanize.Bytes(di.Total), 
            percentage,
        )
}

Upvotes: 9

Related Questions