diff --git a/internal/cloudapi/v1/v1.go b/internal/cloudapi/v1/v1.go index 920034bd1..7b10ba5cb 100644 --- a/internal/cloudapi/v1/v1.go +++ b/internal/cloudapi/v1/v1.go @@ -58,8 +58,7 @@ func (server *Server) Handler(path string) http.Handler { handler := apiHandlers{ server: server, } - RegisterHandlers(e.Group(path, server.IncRequests), &handler) - + RegisterHandlers(e.Group(path, prometheus.MetricsMiddleware), &handler) return e } @@ -76,16 +75,6 @@ func (b binder) Bind(i interface{}, ctx echo.Context) error { return nil } -func (s *Server) IncRequests(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - prometheus.TotalRequests.Inc() - if strings.HasSuffix(c.Path(), "/compose") { - prometheus.ComposeRequests.Inc() - } - return next(c) - } -} - // Compose handles a new /compose POST request func (h *apiHandlers) Compose(ctx echo.Context) error { contentType := ctx.Request().Header["Content-Type"] diff --git a/internal/cloudapi/v2/v2.go b/internal/cloudapi/v2/v2.go index 7520f03e3..88a70a229 100644 --- a/internal/cloudapi/v2/v2.go +++ b/internal/cloudapi/v2/v2.go @@ -64,7 +64,7 @@ func (server *Server) Handler(path string) http.Handler { handler := apiHandlers{ server: server, } - RegisterHandlers(e.Group(path, server.IncRequests), &handler) + RegisterHandlers(e.Group(path, prometheus.MetricsMiddleware), &handler) return e } @@ -82,16 +82,6 @@ func (b binder) Bind(i interface{}, ctx echo.Context) error { return nil } -func (s *Server) IncRequests(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - prometheus.TotalRequests.Inc() - if strings.HasSuffix(c.Path(), "/compose") { - prometheus.ComposeRequests.Inc() - } - return next(c) - } -} - func (h *apiHandlers) GetOpenapi(ctx echo.Context) error { spec, err := GetSwagger() if err != nil { diff --git a/internal/prometheus/middleware.go b/internal/prometheus/middleware.go new file mode 100644 index 000000000..26c88edc8 --- /dev/null +++ b/internal/prometheus/middleware.go @@ -0,0 +1,20 @@ +package prometheus + +import ( + "strings" + + "github.com/labstack/echo/v4" + "github.com/prometheus/client_golang/prometheus" +) + +func MetricsMiddleware(next echo.HandlerFunc) echo.HandlerFunc { + return func(ctx echo.Context) error { + TotalRequests.Inc() + if strings.HasSuffix(ctx.Path(), "/compose") { + ComposeRequests.Inc() + } + timer := prometheus.NewTimer(httpDuration.WithLabelValues(ctx.Path())) + defer timer.ObserveDuration() + return next(ctx) + } +}