๐Item Store API LabLAB
Item Store API Lab
Build a small in-memory REST-style API for items. All testing is done with net/http/httptest โ no real server needed.
Data type
Use a package-level map as storage:
Endpoints
Register all routes on an http.NewServeMux().
GET /items
- Marshal the full contents of
storeas a JSON array - Respond with status 200
GET /items/{id}
- Use
strings.TrimPrefixto extract the ID from the path (e.g.strings.TrimPrefix(r.URL.Path, "/items/")) - If found, respond with the item JSON and status 200
- If not found, respond with body
"not found"and status 404
POST /items
- Decode the JSON request body into an
Item - Store it in
storeby its ID field - Respond with status 201 (Created)
Middleware
Write withContentType(next http.Handler) http.Handler that sets the Content-Type: application/json header on every response before delegating to the inner handler.
Wrap the entire mux with this middleware.
Testing in main
Use httptest.NewRecorder and httptest.NewRequest to exercise all three endpoints:
- POST
{"id":"1","name":"Widget","price":9.99}to/itemsโ expect status 201 - GET
/itemsโ expect the response body to contain"Widget" - GET
/items/1โ expect status 200 and"id":"1"in the body - GET
/items/999โ expect status 404
Print each status code and relevant body excerpt so the output makes the results visible.
โ Enter (Mac) ยท Ctrl+Enter (Win/Linux)
โ Enter (Mac) ยท Ctrl+Enter (Win/Linux)