Files
zogo/monitor/mem.go
T
4566704 30a0889ffa feat(monitor): 自 go-hua 迁入系统资源监控
- Start 后台每秒采集(CPU/内存/磁盘/网络/进程/连接/主机), GetInfo 取快照
- 基于 gopsutil, 附测试、examples/monitor 例程与包 README
2026-09-20 12:29:37 +08:00

68 lines
1.7 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package monitor
import (
"fmt"
"strconv"
"github.com/shirou/gopsutil/v3/mem"
)
// SwapDevice 交换分区设备信息
type SwapDevice struct {
Name string `json:"name"`
UsedBytes uint64 `json:"usedBytes"`
FreeBytes uint64 `json:"freeBytes"`
}
// MemInfo 内存信息(总量/已用/可用/使用率等,gopsutil mem.VirtualMemoryStat)
type MemInfo struct {
Total uint64 `json:"total"`
Available uint64 `json:"available"`
Used uint64 `json:"used"`
Free uint64 `json:"free"`
UsedPercent float64 `json:"usedPercent"`
SwapTotal uint64 `json:"swapTotal"`
SwapAvailable uint64 `json:"SwapAvailable"`
SwapUsed uint64 `json:"swapUsed"`
SwapFree uint64 `json:"swapFree"`
SwapUsedPercent float64 `json:"swapUsedPercent"`
SwapDevices []SwapDevice `json:"swapDevices"`
}
// getMemInfo 采集内存与交换区信息
func getMemInfo() (MemInfo, error) {
info := MemInfo{}
v, err := mem.VirtualMemory()
if err != nil {
return info, err
}
info.Total = v.Total
info.Used = v.Used
info.Free = v.Free
info.UsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", v.UsedPercent), 64)
s, err := mem.SwapMemory()
if err != nil {
return info, err
}
info.SwapTotal = s.Total
info.SwapUsed = s.Used
info.SwapFree = s.Free
info.SwapUsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", s.UsedPercent), 64)
devices, err := mem.SwapDevices()
if err != nil {
return info, err
}
for _, device := range devices {
info.SwapDevices = append(info.SwapDevices, SwapDevice{
Name: device.Name,
UsedBytes: device.UsedBytes,
FreeBytes: device.FreeBytes,
})
}
return info, err
}