代码拉取完成,页面将自动刷新
package middle
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// 全局 Prometheus 指标
var (
CustomerRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "custom_http_requests_total",
Help: "Total number of HTTP requests.",
},
[]string{"path", "method", "status"},
)
ThrottleCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "throttle_counter_total",
Help: "Total number of requests that passed the throttle.",
},
[]string{"resource", "status"},
)
)
func init() {
// 注册全局 Prometheus 指标
prometheus.MustRegister(CustomerRequestsTotal)
prometheus.MustRegister(ThrottleCounter)
}
// PrometheusMiddleware 记录常规的 HTTP 请求统计数据
func PrometheusMiddle() gin.HandlerFunc {
return func(c *gin.Context) {
// 记录请求总数
status := c.Writer.Status()
CustomerRequestsTotal.WithLabelValues(c.FullPath(), c.Request.Method, fmt.Sprintf("%d", status)).Inc()
// 处理请求
c.Next()
}
}
// 在 Gin 路由中注册 Prometheus 处理程序
func RegisterPrometheus(port int) {
http.Handle("/metrics", promhttp.Handler())
go func() {
fmt.Printf(" - using prometheus: %v\n", port)
http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}()
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。