1、获取整个磁盘的总量、已使用量、使用率
Go
package main
import (
"fmt"
"github.com/shirou/gopsutil/disk"
"log"
)
func main() {
// 获取所有挂载点的磁盘使用率信息
partitions, err := disk.Partitions(false)
if err != nil {
log.Fatalf("Error getting partitions: %v", err)
}
var total uint64
var used uint64
for _, partition := range partitions {
usage, err := disk.Usage(partition.Mountpoint)
if err != nil {
log.Printf("Error getting usage for %s: %v", partition.Mountpoint, err)
continue
}
total += usage.Total
used += usage.Used
}
// 计算总使用率
usagePercent := float64(used) / float64(total) * 100
// 打印总磁盘使用率信息
fmt.Printf("Total Disk Usage: %.2f%%\n", usagePercent)
fmt.Printf("Total: %v GB\n", total/1024/1024/1024)
fmt.Printf("Used: %v GB\n", used/1024/1024/1024)
fmt.Printf("Free: %v GB\n", (total-used)/1024/1024/1024)
}
2、获取某个目录的空间总量、剩余量、使用量、使用率
比如:下面的查询根目录的空间大小、剩余空间、使用空间、使用绿
Go
package main
"github.com/shirou/gopsutil/disk"
)
func main() {
// 获取磁盘使用率信息
usage, err := disk.Usage("/")
if err != nil {
fmt.Printf("Error getting disk usage: %v\n", err)
return
}
// 打印磁盘使用率信息
fmt.Printf("Disk Usage of /:\n")
fmt.Printf("Total: %v GB\n", usage.Total/1024/1024/1024)
fmt.Printf("Free: %v GB\n", usage.Free/1024/1024/1024)
fmt.Printf("Used: %v GB\n", usage.Used/1024/1024/1024)
fmt.Printf("Used Percent: %.2f%%\n", usage.UsedPercent)
}