0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 10
click for more info
No active XP Potion
Accept a Quest
Login to submit answers
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.
The Boot.dev CLI requires you to be signed in to submit your solution!
Copy/paste one of the following commands into your terminal:
Run
bootdev run a13ffa72-18b9-49f7-81a9-c5a17d007b3a
Submit
bootdev run a13ffa72-18b9-49f7-81a9-c5a17d007b3a -s
bootdev config base_url <url>
Run the CLI commands to test your solution.
Cache-Control: no-cache
Cache-Control: no-cache
Cache-Control: no-cache
Cache-Control: no-cache
Login to view solution
Using the Bootdev CLI
The Bootdev CLI is the only way to submit your solution for this type of lesson. We need to be able to run commands in your environment to verify your solution.
You can install it here. It's a Go program hosted on GitHub, so you'll need Go installed as well. Instructions are on the GitHub page.