24 lines
616 B
Go
24 lines
616 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/felixge/httpsnoop"
|
|
"github.com/go-chi/chi/v5"
|
|
)
|
|
|
|
type RequestMetrics interface {
|
|
ObserveRequest(method, route string, status int, duration time.Duration)
|
|
}
|
|
|
|
func CollectMetrics(metrics RequestMetrics) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
captured := httpsnoop.CaptureMetrics(next, w, r)
|
|
route := chi.RouteContext(r.Context()).RoutePattern()
|
|
metrics.ObserveRequest(r.Method, route, captured.Code, captured.Duration)
|
|
})
|
|
}
|
|
}
|