feat: metrics, makefile

This commit is contained in:
2026-04-29 15:38:06 +02:00
parent 7affd35ae4
commit 0892c33b13
5 changed files with 72 additions and 1 deletions
+34
View File
@@ -2,13 +2,16 @@ package main
import (
"errors"
"expvar"
"fmt"
"net"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/felixge/httpsnoop"
"golang.org/x/time/rate"
"greenlight.debuggingjon.dev/internal/data"
"greenlight.debuggingjon.dev/internal/validator"
@@ -280,3 +283,34 @@ func (app *application) enableCORS(next http.Handler) http.Handler {
next.ServeHTTP(w, r)
})
}
func (app *application) metrics(next http.Handler) http.Handler {
totalRequestsReceived := expvar.NewInt("total_requests_received")
totalResponsesSent := expvar.NewInt("total_responses_sent")
totalProcessingTimeMicroseconds := expvar.NewInt("total_processing_time_μs")
// Declare a new expvar map to hold the count of responses for each HTTP status
// code.
totalResponsesSentByStatus := expvar.NewMap("total_responses_sent_by_status")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Increment the requests received count, like before.
totalRequestsReceived.Add(1)
// Call the httpsnoop.CaptureMetrics() function, passing in the next handler in
// the chain along with the existing http.ResponseWriter and http.Request. This
// returns the metrics struct that we saw above.
metrics := httpsnoop.CaptureMetrics(next, w, r)
// Increment the response sent count, like before.
totalResponsesSent.Add(1)
// Get the request processing time in microseconds from httpsnoop and increment
// the cumulative processing time.
totalProcessingTimeMicroseconds.Add(metrics.Duration.Microseconds())
// Use the Add() method to increment the count for the given status code by 1.
// Note that the expvar map is string-keyed, so we need to use the strconv.Itoa()
// function to convert the status code (which is an integer) to a string.
totalResponsesSentByStatus.Add(strconv.Itoa(metrics.Code), 1)
})
}
+1 -1
View File
@@ -31,5 +31,5 @@ func (app *application) routes() http.Handler {
// Register a new GET /debug/vars endpoint pointing to the expvar 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)))))
}