What We’re Building
A REST API with these endpoints:| Method | Path | Description |
|---|---|---|
| GET | /api/todos | List all todos |
| POST | /api/todos | Create a todo |
| GET | /api/todos/:id | Get a todo by ID |
| PUT | /api/todos/:id | Update a todo |
| DELETE | /api/todos/:id | Delete a todo |
Step 1: Create the Project
{"status":"ok"}.
Step 2: Create the Todo Feature
Create the feature directory:feature/todos/http.go:
Step 3: Implement List Handler
Add tofeature/todos/http.go:
Step 4: Implement Create Handler
Add tofeature/todos/http.go:
Step 5: Implement Get Handler
Add tofeature/todos/http.go:
Step 6: Implement Update Handler
Add tofeature/todos/http.go:
Step 7: Implement Delete Handler
Add tofeature/todos/http.go:
Step 8: Register Routes
Updateapp/api/app.go to include the store:
app/api/routes.go:
Step 9: Test the API
Start the server:List (empty)
[]
Create
Create Another
List All
Get One
Update
Delete
Complete Code
Here’s the completefeature/todos/http.go:
What You Learned
- Feature organization - Grouping related code together
- Handler factories - Functions that return handlers
- Dependency injection - Passing the store to handlers
- CRUD operations - Create, Read, Update, Delete patterns
- Input validation - Checking required fields
- Error responses - Returning appropriate status codes
Next Steps
Add a Database
Replace in-memory store with a real database
Contract Template
Learn about multi-protocol APIs
Add Middleware
Add logging, auth, and more
Error Handling
Improve error responses