feat(monitor): 自 go-hua 迁入系统资源监控

- Start 后台每秒采集(CPU/内存/磁盘/网络/进程/连接/主机), GetInfo 取快照
- 基于 gopsutil, 附测试、examples/monitor 例程与包 README
This commit is contained in:
2026-09-20 12:29:37 +08:00
parent 138c929bd4
commit 30a0889ffa
11 changed files with 963 additions and 0 deletions
+93
View File
@@ -0,0 +1,93 @@
package monitor
import (
"fmt"
"strconv"
"github.com/shirou/gopsutil/v3/cpu"
)
// CPU CPU 采集信息
type CPU struct {
CPU int32 `json:"cpu"`
VendorID string `json:"vendorId"`
ModelName string `json:"modelName"`
Mhz float64 `json:"mhz"`
Cores int32 `json:"cores"`
}
// CpuBaseInfo CPU 基本信息(型号/核心数/频率等,gopsutil cpu.Info)
type CpuBaseInfo struct {
Core int `json:"core"`
Logic int `json:"logic"`
Info []CPU `json:"info"`
}
// CpuInfo 每逻辑核心使用率
type CpuInfo struct {
CpuBaseInfo
CpuUsedInfo
}
// CpuUsedInfo CPU 使用率明细(含用户/系统/空闲等占比)
type CpuUsedInfo struct {
UsedPercent float64 `json:"usedPercent"`
Used []float64 `json:"used"`
}
// CpuInfoLite 精简版 CPU 信息
type CpuInfoLite struct {
Core int `json:"core"`
Logic int `json:"logic"`
Name []string `json:"name"`
UsedPercent float64 `json:"usedPercent"`
Used []float64 `json:"used"`
}
// getCpuInfo 采集 CPU 基础信息与每核心使用率
func getCpuInfo() (CpuInfo, error) {
info := CpuInfo{}
cpuInfo, err := cpu.Info()
if err != nil {
return info, err
}
info.Info = make([]CPU, len(cpuInfo))
for i, v := range cpuInfo {
info.Info[i].CPU = v.CPU
info.Info[i].VendorID = v.VendorID
info.Info[i].ModelName = v.ModelName
info.Info[i].Mhz = v.Mhz
info.Info[i].Cores = v.Cores
}
core, err := cpu.Counts(false)
if err != nil {
return info, err
}
logic, err := cpu.Counts(true)
if err != nil {
return info, err
}
info.Core = core
info.Logic = logic
return info, nil
}
// getCpuUsed 采集 CPU 使用率明细
func getCpuUsed() (CpuUsedInfo, error) {
info := CpuUsedInfo{}
percent, err := cpu.Percent(0, true)
if err != nil {
return info, err
}
var usedPercent float64 = 0.0
for i, v := range percent {
percent[i], _ = strconv.ParseFloat(fmt.Sprintf("%.1f", v), 64)
usedPercent += v
}
usedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", usedPercent/float64(len(percent))), 64)
info.Used = percent
info.UsedPercent = usedPercent
return info, nil
}