34 lines
857 B
Go
34 lines
857 B
Go
package middleware
|
|
|
|
import (
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"go-sms/internal/pkg/metrics"
|
|
)
|
|
|
|
// Metrics HTTP 指标埋点中间件(Day 13):
|
|
// 请求总数(method/route/status)、耗时分布(method/route)、在途数(Gauge)。
|
|
// route 使用路由模板(c.FullPath)避免路径参数导致标签基数爆炸;
|
|
// 未匹配路由记为 "unmatched"。
|
|
func Metrics() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
route := c.FullPath()
|
|
if route == "" {
|
|
route = "unmatched"
|
|
}
|
|
start := time.Now()
|
|
|
|
metrics.HTTPRequestsInFlight.Inc()
|
|
c.Next()
|
|
metrics.HTTPRequestsInFlight.Dec()
|
|
|
|
status := strconv.Itoa(c.Writer.Status())
|
|
metrics.HTTPRequestsTotal.WithLabelValues(c.Request.Method, route, status).Inc()
|
|
metrics.HTTPRequestDuration.WithLabelValues(c.Request.Method, route).
|
|
Observe(time.Since(start).Seconds())
|
|
}
|
|
}
|