58 lines
1.3 KiB
Go
58 lines
1.3 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
)
|
|
|
|
var (
|
|
httpRequestsTotal = prometheus.NewCounterVec(
|
|
prometheus.CounterOpts{
|
|
Name: "http_requests_total",
|
|
Help: "Total number of HTTP requests",
|
|
},
|
|
[]string{"method", "path", "status"},
|
|
)
|
|
|
|
httpRequestDuration = prometheus.NewHistogramVec(
|
|
prometheus.HistogramOpts{
|
|
Name: "http_request_duration_seconds",
|
|
Help: "Duration of HTTP requests",
|
|
Buckets: prometheus.DefBuckets,
|
|
},
|
|
[]string{"method", "path", "status"},
|
|
)
|
|
)
|
|
|
|
func init() {
|
|
prometheus.MustRegister(httpRequestsTotal, httpRequestDuration)
|
|
}
|
|
|
|
func PrometheusMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
rr := &responseRecorder{ResponseWriter: w, statusCode: 200}
|
|
next.ServeHTTP(rr, r)
|
|
duration := time.Since(start)
|
|
|
|
method := r.Method
|
|
path := r.URL.Path
|
|
status := strconv.Itoa(rr.statusCode)
|
|
|
|
httpRequestsTotal.WithLabelValues(method, path, status).Inc()
|
|
httpRequestDuration.WithLabelValues(method, path, status).Observe(duration.Seconds())
|
|
})
|
|
}
|
|
|
|
type responseRecorder struct {
|
|
http.ResponseWriter
|
|
statusCode int
|
|
}
|
|
|
|
func (rr *responseRecorder) WriteHeader(code int) {
|
|
rr.statusCode = code
|
|
rr.ResponseWriter.WriteHeader(code)
|
|
}
|