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 }