It's frequently useful to have a way to store and access state in our handlers. For example, we might want to keep track of the number of requests we've received, or we may want to pass around an open connection to a database, or credentials to an API.
The product managers at Chirpy want to know how many requests are being made to serve our homepage - in essence, they want to know how many people are viewing the site!
They have asked for a simple HTTP endpoint they can hit to get the number of requests that have been processed. It will return the count as plain text in the response body.
For now, they just want the number of requests that have been processed since the last time the server was started, we don't need to worry about saving the data between restarts.
type apiConfig struct {
fileserverHits atomic.Int32
}
The atomic.Int32 type is a really cool standard-library type that allows us to safely increment and read an integer value across multiple goroutines (HTTP requests).
func (cfg *apiConfig) middlewareMetricsInc(next http.Handler) http.Handler {
// ...
}
The atomic.Int32 type has an .Add() method, use it to safely increment the number of fileserverHits.
mux.Handle("/app/", apiCfg.middlewareMetricsInc(handler))
Hits: x
Where x is the number of requests that have been processed. This handler should be a method on the *apiConfig struct so that it can access the fileserverHits data.
It should follow the same design as the previous handlers.
Remember, similar to the metrics endpoint, /reset will need to be a method on the *apiConfig struct so that it can also access the fileserverHits
Run and submit the CLI tests.