ADVERTISEMENT
ADVERTISEMENT

How to get the disk usage information in Golang?

Here, we will learn to get the disk usage information in Golang.
Submitted by IncludeHelp, on November 12, 2021

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.

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

Golang syscall Package Programs »



ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.