get system free disk space in go

To get the free disk space of the system in Go, we can use the syscall package and make use of native system calls to retrieve the required information. Here's an example code snippet that accomplishes this task:

main.go
package main

import (
    "fmt"
    "syscall"
)

func main() {
    var stat syscall.Statfs_t
    wd, err := syscall.Getwd()
    if err != nil {
        panic(err)
    }
    err = syscall.Statfs(wd, &stat)
    if err != nil {
        panic(err)
    }
    free := stat.Bavail * uint64(stat.Bsize)
    fmt.Printf("Free disk space: %v bytes\n", free)
}
350 chars
21 lines

This code snippet retrieves the current working directory of the program using syscall.Getwd() and then uses syscall.Statfs() to get information about the filesystem that the working directory is located on. This information is then used to calculate the amount of free disk space available on the system, which is printed to the console.

Note that the syscall.Statfs_t struct contains information about the filesystem, including the total number of blocks and the number of available blocks. The size of each block can be obtained from the stat.Bsize field, which is multiplied by the number of available blocks (stat.Bavail) to get the total amount of free disk space.

gistlibby LogSnag