4 changed files with 111 additions and 0 deletions
@ -0,0 +1,92 @@ |
|||
package core |
|||
|
|||
import ( |
|||
"fmt" |
|||
"log" |
|||
"net/http" |
|||
"time" |
|||
|
|||
"github.com/shirou/gopsutil/v3/cpu" |
|||
"github.com/shirou/gopsutil/v3/disk" |
|||
"github.com/shirou/gopsutil/v3/mem" |
|||
"github.com/shirou/gopsutil/v3/net" |
|||
"github.com/shirou/gopsutil/v3/process" |
|||
) |
|||
|
|||
// 系统监控
|
|||
func SysMonitor(w http.ResponseWriter, r *http.Request) { |
|||
// 设置 CORS 头部
|
|||
w.Header().Set("Access-Control-Allow-Origin", "*") |
|||
w.Header().Set("Access-Control-Allow-Methods", "GET") |
|||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type") |
|||
|
|||
// 磁盘容量信息
|
|||
diskInfo, err := disk.Usage("/") |
|||
if err != nil { |
|||
fmt.Println("获取磁盘信息失败:", err) |
|||
return |
|||
} else { |
|||
fmt.Println("=== 磁盘信息 ===") |
|||
fmt.Printf("总容量: %.2f GB\n", float64(diskInfo.Total)/1024/1024/1024) |
|||
fmt.Printf("已使用: %.2f GB\n", float64(diskInfo.Used)/1024/1024/1024) |
|||
fmt.Printf("可用空间: %.2f GB\n", float64(diskInfo.Free)/1024/1024/1024) |
|||
fmt.Printf("使用率: %.2f%%\n", diskInfo.UsedPercent) |
|||
} |
|||
|
|||
// 获取CPU占用率 (需要等待1秒来计算)
|
|||
cpuPercent, err := cpu.Percent(time.Second, false) |
|||
if err != nil { |
|||
log.Printf("获取CPU信息失败: %v", err) |
|||
} else { |
|||
fmt.Println("\n=== CPU信息 ===") |
|||
fmt.Printf("CPU使用率: %.2f%%\n", cpuPercent[0]) |
|||
} |
|||
|
|||
// 获取内存占用信息
|
|||
memInfo, err := mem.VirtualMemory() |
|||
if err != nil { |
|||
log.Printf("获取内存信息失败: %v", err) |
|||
} else { |
|||
fmt.Println("\n=== 内存信息 ===") |
|||
fmt.Printf("总内存: %.2f GB\n", float64(memInfo.Total)/1024/1024/1024) |
|||
fmt.Printf("已使用: %.2f GB\n", float64(memInfo.Used)/1024/1024/1024) |
|||
fmt.Printf("可用内存: %.2f GB\n", float64(memInfo.Available)/1024/1024/1024) |
|||
fmt.Printf("内存使用率: %.2f%%\n", memInfo.UsedPercent) |
|||
} |
|||
|
|||
// 获取网络流量信息
|
|||
netIO, err := net.IOCounters(false) |
|||
if err != nil { |
|||
log.Printf("获取网络信息失败: %v", err) |
|||
} else if len(netIO) > 0 { |
|||
fmt.Println("\n=== 网络信息 ===") |
|||
fmt.Printf("总接收: %.2f MB\n", float64(netIO[0].BytesRecv)/1024/1024) |
|||
fmt.Printf("总发送: %.2f MB\n", float64(netIO[0].BytesSent)/1024/1024) |
|||
fmt.Printf("接收包数: %d\n", netIO[0].PacketsRecv) |
|||
fmt.Printf("发送包数: %d\n", netIO[0].PacketsSent) |
|||
} |
|||
|
|||
// 获取系统进程信息 (只获取前5个进程)
|
|||
processes, err := process.Processes() |
|||
if err != nil { |
|||
log.Printf("获取进程信息失败: %v", err) |
|||
} else { |
|||
fmt.Println("\n=== 进程信息 (前5个) ===") |
|||
count := 0 |
|||
for _, p := range processes { |
|||
if count >= 5 { |
|||
break |
|||
} |
|||
|
|||
pid := p.Pid |
|||
name, _ := p.Name() |
|||
cpuPercent, _ := p.CPUPercent() |
|||
memPercent, _ := p.MemoryPercent() |
|||
|
|||
fmt.Printf("PID: %d, 名称: %s, CPU使用率: %.2f%%, 内存使用率: %.2f%%\n", |
|||
pid, name, cpuPercent, memPercent) |
|||
count++ |
|||
} |
|||
} |
|||
|
|||
} |
|||
Loading…
Reference in new issue