feat: 完善后端脚手架基础能力
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
)
|
||||
|
||||
var (
|
||||
httpRequests = prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Name: "skeleton_http_requests_total",
|
||||
Help: "Total number of HTTP requests.",
|
||||
}, []string{"method", "route", "status"})
|
||||
httpDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Name: "skeleton_http_request_duration_seconds",
|
||||
Help: "HTTP request latency in seconds.",
|
||||
Buckets: prometheus.DefBuckets,
|
||||
}, []string{"method", "route", "status"})
|
||||
)
|
||||
|
||||
func init() {
|
||||
prometheus.MustRegister(httpRequests, httpDuration)
|
||||
}
|
||||
|
||||
func Metrics() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
started := time.Now()
|
||||
c.Next()
|
||||
route := c.FullPath()
|
||||
if route == "" {
|
||||
route = "unmatched"
|
||||
}
|
||||
status := strconv.Itoa(c.Writer.Status())
|
||||
httpRequests.WithLabelValues(c.Request.Method, route, status).Inc()
|
||||
httpDuration.WithLabelValues(c.Request.Method, route, status).Observe(time.Since(started).Seconds())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user