×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

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 [Last updated : March 05, 2023]

Getting 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.

Syntax

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

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

Golang code to get the disk usage information

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 »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.