All checks were successful
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 2m16s
53 lines
1.3 KiB
Go
53 lines
1.3 KiB
Go
package hello
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
"github.com/prometheus/client_golang/prometheus/promauto"
|
|
)
|
|
|
|
var (
|
|
httpRequestsTotal = promauto.NewCounterVec(prometheus.CounterOpts{
|
|
Name: "http_requests_total",
|
|
Help: "Total number of HTTP requests.",
|
|
}, []string{"path", "method", "status"})
|
|
|
|
httpRequestDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
|
|
Name: "http_request_duration_seconds",
|
|
Help: "Duration of HTTP requests.",
|
|
Buckets: prometheus.DefBuckets,
|
|
}, []string{"path", "method", "status"})
|
|
)
|
|
|
|
// Middleware wraps an http.HandlerFunc with Prometheus metrics
|
|
func Middleware(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
|
|
ww := &responseWriter{ResponseWriter: w, status: http.StatusOK}
|
|
|
|
next(ww, r)
|
|
|
|
duration := time.Since(start).Seconds()
|
|
status := strconv.Itoa(ww.status)
|
|
path := r.URL.Path
|
|
method := r.Method
|
|
|
|
httpRequestsTotal.WithLabelValues(path, method, status).Inc()
|
|
httpRequestDuration.WithLabelValues(path, method, status).Observe(duration)
|
|
}
|
|
}
|
|
|
|
type responseWriter struct {
|
|
http.ResponseWriter
|
|
status int
|
|
}
|
|
|
|
func (rw *responseWriter) WriteHeader(code int) {
|
|
rw.status = code
|
|
rw.ResponseWriter.WriteHeader(code)
|
|
}
|