Q:

How to get the disk usage information in Golang?

belongs to collection: Golang syscall Package Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Syntax:

func Statfs(path string, buf *Statfs_t) (err error)

Consider the below example demonstrating how to get disk usage information in Golang?

package main

import (
	"fmt"
	"syscall"
)

// Creating structure for DiskStatus
type DiskStatus struct {
	All  uint64 `json:"All"`
	Used uint64 `json:"Used"`
	Free uint64 `json:"Free"`
}

// Function to get
// disk usage of path/disk
func DiskUsage(path string) (disk DiskStatus) {
	fs := syscall.Statfs_t{}
	err := syscall.Statfs(path, &fs)
	if err != nil {
		return
	}
	disk.All = fs.Blocks * uint64(fs.Bsize)
	disk.Free = fs.Bfree * uint64(fs.Bsize)
	disk.Used = disk.All - disk.Free
	return
}

// Defining constants to convert size units
const (
	B  = 1
	KB = 1024 * B
	MB = 1024 * KB
	GB = 1024 * MB
)

func main() {
	// Getting filesystem statistics
	disk := DiskUsage("/")
	fmt.Printf("All: %.2f GB\n", float64(disk.All)/float64(GB))
	fmt.Printf("Used: %.2f GB\n", float64(disk.Used)/float64(GB))
	fmt.Printf("Free: %.2f GB\n", float64(disk.Free)/float64(GB))
}

Output

All: 28.90 GB
Used: 24.47 GB
Free: 4.44 GB

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

How to get the environment variables using syscall... >>
<< How to change the working directory using syscall ...