From bb8922f4292f95457ba9b7039ea4bc540bb622c2 Mon Sep 17 00:00:00 2001 From: lbenedar Date: Tue, 24 Mar 2026 16:58:19 +0300 Subject: [PATCH] ch19.4 --- cmd/api/middleware.go | 20 ++++++++++++++++++++ cmd/api/routes.go | 2 +- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/cmd/api/middleware.go b/cmd/api/middleware.go index d09e7ad..07f0bd5 100644 --- a/cmd/api/middleware.go +++ b/cmd/api/middleware.go @@ -2,6 +2,7 @@ package main import ( "errors" + "expvar" "fmt" "net" "net/http" @@ -199,3 +200,22 @@ func (app *application) enableCORS(next http.Handler) http.Handler { next.ServeHTTP(w, r) }) } + +func (app *application) metrics(next http.Handler) http.Handler { + var ( + totalRequestsReceived = expvar.NewInt("total_requests_received") + totalResponseSent = expvar.NewInt("total_responses_sent") + totalProcessingTimeMicroseconds = expvar.NewInt("total_processing_time_μs") + ) + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + + totalRequestsReceived.Add(1) + next.ServeHTTP(w, r) + totalResponseSent.Add(1) + + duration := time.Since(start).Microseconds() + totalProcessingTimeMicroseconds.Add(duration) + }) +} diff --git a/cmd/api/routes.go b/cmd/api/routes.go index c6a67ed..a112c81 100644 --- a/cmd/api/routes.go +++ b/cmd/api/routes.go @@ -28,5 +28,5 @@ func (app *application) routes() http.Handler { router.Handler(http.MethodGet, "/debug/vars", expvar.Handler()) - return app.recoverPanic(app.enableCORS(app.rateLimit(app.authenticate(router)))) + return app.metrics(app.recoverPanic(app.enableCORS(app.rateLimit(app.authenticate(router))))) }