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.
To display information of all file system statistics in GB (Gigabyte) use the option as 'df -h'.
Here, we will learn to get the disk usage information in Golang. In the Go programming language, to get disk usage information – we use the Statfs() function of the syscall package. The Statfs() function is used to get the filesystem statistics.
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.
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,
)
}
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