很多时候,我们写一个 Go Web 服务,部署上线之后,发现缺少基本的可观测性:
- 请求量多少?
- 内存和磁盘还够用吗?
- 服务器 CPU 是否出现瓶颈?
如果为了这些问题单独部署 node_exporter 或引入 gopsutil,往往会增加复杂度和依赖。
而 go-commons 就提供了一个优雅的解决方案 —— 它是一个纯 Go 的轻量工具库,开箱即用,无需三方依赖。
场景:让每个服务都自带体检功能
想象一下,你写了一个电商后台服务,或者是一个 IM 服务。除了业务接口,你希望它能自带一个 /health 或 /metrics 接口,实时返回:
- 当前请求数(QPS)
- 内存使用情况
- CPU 负载
- 磁盘剩余空间
这样即使没有外部监控系统,你也能通过浏览器或 curl 直接看到服务器的健康状态。
代码示例:内置健康检查接口
下面这段代码演示了如何用 go-commons 实现一个 /health 接口:
package main
import (
"encoding/json"
"net/http"
"github.com/Rodert/go-commons/systemutils/cpuutils"
"github.com/Rodert/go-commons/systemutils/memutils"
"github.com/Rodert/go-commons/systemutils/diskutils"
)
type HealthStatus struct {
CPUUsage float64 `json:"cpu_usage"`
LoadAvg []float64 `json:"load_avg"`
MemUsedMB uint64 `json:"mem_used_mb"`
MemTotalMB uint64 `json:"mem_total_mb"`
DiskUsedGB uint64 `json:"disk_used_gb"`
DiskTotalGB uint64 `json:"disk_total_gb"`
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
status := HealthStatus{}
// CPU
if cpuInfo, err := cpuutils.GetCPUInfo(); err == nil {
status.CPUUsage = cpuInfo.UsagePercent
status.LoadAvg = cpuInfo.LoadAvg
}
// 内存
if memInfo, err := memutils.GetMemInfo(); err == nil {
status.MemUsedMB = memInfo.Used / 1024 / 1024
status.MemTotalMB = memInfo.Total / 1024 / 1024
}
// 磁盘
if diskInfo, err := diskutils.GetDiskInfo("/"); err == nil {
status.DiskUsedGB = diskInfo.Used / 1024 / 1024 / 1024
status.DiskTotalGB = diskInfo.Total / 1024 / 1024 / 1024
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(status)
}
func main() {
http.HandleFunc("/health", healthHandler)
http.ListenAndServe(":8080", nil)
}运行后访问:
curl http://localhost:8080/health输出示例:
{
"cpu_usage": 12.5,
"load_avg": [0.23, 0.45, 0.50],
"mem_used_mb": 512,
"mem_total_mb": 4096,
"disk_used_gb": 20,
"disk_total_gb": 100
}这样,你的服务就天然带了“健康报告”。
为什么选择 go-commons?
- 零依赖:无需 gopsutil、无需 node_exporter,直接用标准库 + go-commons。
- 跨平台支持:Linux、macOS、Windows 都能运行。
- 更轻量:适合嵌入到任何 Go 应用,不需要单独部署额外组件。
- 文档完整:有在线 API 文档(点击查看),上手成本低。
一起完善 go-commons 🚀
目前 go-commons 已经支持 CPU、内存、磁盘的指标采集,接下来计划:
- 增加网络流量、带宽监控
- 增加进程数、线程数采集
- 和 Prometheus 生态更紧密的集成
欢迎大家一起来参与贡献:
👉 项目地址:https://github.com/Rodert/go-commons
如果你也希望 每个 Go 服务都能“自带体检报告”,快来试试 go-commons,并加入一起打磨它吧!
















