Get amount of free disk space using Go
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"
h := windows.MustLoadDLL("kernel32.dll")
c := h.MustFindProc("GetDiskFreeSpaceExW")
var freeBytes int64
_, _, err := c.Call(uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(wd))),
uintptr(unsafe.Pointer(&freeBytes)), nil, nil)
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.
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,
)
}
}
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,
)
}