Retrieving Free Disk Space in Go Across Multiple Platforms
In this article, we explore a solution to dynamically retrieve the free and total size of a storage volume using Go, regardless of the operating system (Windows, Linux, Mac). This solution eliminates the need for external commands like df -h or manual calculations.
For POSIX-based systems, we leverage the sys.unix.Statfs function to access the Statfs_t structure. For instance, to obtain the free space for the current working directory in bytes:
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))
In the case of Windows, we take the syscall approach. Here's an updated example using the newer 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)
Don't hesitate to extend these examples into a cross-platform package for broader usage. For guidance on cross-platform implementation, consult the build tool's help documentation.
The above is the detailed content of How Can I Get Free Disk Space in Go Across Different Operating Systems?. For more information, please follow other related articles on the PHP Chinese website!