Go语言系统信息获取示例
本项目演示了如何在Go语言中获取系统信息,类似Python的platform
模块功能。
主要功能
标准库 runtime
包
- Go版本信息
- 操作系统类型
- 系统架构
- CPU核心数
- 内存统计信息
- Goroutine信息
第三方库 gopsutil
- 主机信息: 主机名、运行时间、操作系统版本、内核版本等
- CPU信息: CPU型号、厂商、频率、核心数、使用率等
- 内存信息: 总内存、已用内存、缓存、交换分区等
- 磁盘信息: 磁盘分区、使用率、文件系统等
- 网络信息: 网络接口、IP地址、网络IO统计等
项目结构
.
├── main.go # 主程序,展示基本系统信息
├── system_info_test.go # 详细的测试文件,包含所有功能测试
├── go.mod # Go模块文件
└── go.sum # 依赖校验文件
依赖
主要依赖第三方库:
github.com/shirou/gopsutil/v3
- 跨平台的系统信息获取库
安装和运行
-
初始化项目:
go mod init system-info-test go get github.com/shirou/gopsutil/v3 go mod tidy
-
运行主程序:
go run main.go
-
运行详细测试:
go test -v
-
运行性能测试:
go test -bench=.
-
运行特定测试:
go test -v -run TestCPUInfo # 只测试CPU信息 go test -v -run TestMemoryInfo # 只测试内存信息 go test -v -run TestDiskInfo # 只测试磁盘信息
API对比
Python platform 模块对比
Python platform | Go gopsutil | 功能描述 |
---|---|---|
platform.system() |
runtime.GOOS |
操作系统名称 |
platform.machine() |
runtime.GOARCH |
机器架构 |
platform.processor() |
cpu.Info() |
处理器信息 |
platform.platform() |
host.Info() |
平台信息 |
platform.node() |
host.Info().Hostname |
主机名 |
platform.release() |
host.Info().KernelVersion |
系统发行版本 |
示例代码
package mainimport ("fmt""runtime""github.com/shirou/gopsutil/v3/host""github.com/shirou/gopsutil/v3/cpu""github.com/shirou/gopsutil/v3/mem"
)func main() {// 获取基本信息fmt.Printf("操作系统: %s\n", runtime.GOOS)fmt.Printf("架构: %s\n", runtime.GOARCH)fmt.Printf("CPU核心数: %d\n", runtime.NumCPU())// 获取主机信息hostInfo, _ := host.Info()fmt.Printf("主机名: %s\n", hostInfo.Hostname)fmt.Printf("平台: %s %s\n", hostInfo.Platform, hostInfo.PlatformVersion)// 获取CPU信息cpuInfo, _ := cpu.Info()if len(cpuInfo) > 0 {fmt.Printf("CPU: %s\n", cpuInfo[0].ModelName)}// 获取内存信息memInfo, _ := mem.VirtualMemory()fmt.Printf("总内存: %d MB\n", memInfo.Total/1024/1024)fmt.Printf("内存使用率: %.2f%%\n", memInfo.UsedPercent)
}
测试功能
测试文件 system_info_test.go
包含以下测试:
- TestSystemInfo - 基本系统信息
- TestHostInfo - 主机详细信息
- TestCPUInfo - CPU详细信息和使用率
- TestMemoryInfo - 内存和交换分区信息
- TestDiskInfo - 磁盘分区和使用情况
- TestNetworkInfo - 网络接口和IO统计
- TestAllSystemInfo - 综合测试
- BenchmarkCPUUsage - CPU使用率获取性能测试
- BenchmarkMemoryInfo - 内存信息获取性能测试
跨平台支持
gopsutil
库支持多个操作系统:
- Linux
- Windows
- macOS
- FreeBSD
- OpenBSD
注意事项
- 某些系统信息获取可能需要管理员权限
- 网络信息在不同操作系统上可能有差异
- CPU使用率获取需要一定时间间隔来计算
- 部分功能在虚拟化环境中可能受限
扩展功能
可以进一步扩展获取:
- 进程信息
- 服务信息
- 温度传感器
- GPU信息
- 负载均衡信息
相关资源
- gopsutil GitHub
- Go runtime 包文档
- 系统监控最佳实践