45 lines
1017 B
Go
45 lines
1017 B
Go
package status
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/shirou/gopsutil/v3/mem"
|
|
)
|
|
|
|
type MemoryStatus struct {
|
|
TotalMemory uint64
|
|
UsedMemory uint64
|
|
AvailableMemory uint64
|
|
TotalVirtualMemory uint64
|
|
UsedVirtualMemory uint64
|
|
}
|
|
|
|
func GetMemoryStatus() (*MemoryStatus, error) {
|
|
memoryStatus := &MemoryStatus{}
|
|
|
|
virtualMemoryStat, err := mem.VirtualMemory()
|
|
if err != nil {
|
|
return memoryStatus, err
|
|
}
|
|
|
|
memoryStatus.TotalMemory = virtualMemoryStat.Total
|
|
memoryStatus.UsedMemory = virtualMemoryStat.Used
|
|
memoryStatus.AvailableMemory = virtualMemoryStat.Available
|
|
memoryStatus.TotalVirtualMemory = virtualMemoryStat.Total
|
|
memoryStatus.UsedVirtualMemory = virtualMemoryStat.Used
|
|
|
|
return memoryStatus, nil
|
|
}
|
|
|
|
func FormatMemorySize(size uint64) string {
|
|
const unit = 1024
|
|
if size < unit {
|
|
return fmt.Sprintf("%d B", size)
|
|
}
|
|
div, exp := int64(unit), 0
|
|
for n := size / unit; n >= unit; n /= unit {
|
|
div *= unit
|
|
exp++
|
|
}
|
|
return fmt.Sprintf("%.1f %cB", float64(size)/float64(div), "KMGTPE"[exp])
|
|
}
|