This is a Todo API built with Go and the Chi router, demonstrating best practices for building web applications in Go. It includes authentication, middleware, context usage, and proper project structure.
- Clean and modular project structure
- Chi router with middleware
- Custom middleware (logging, CORS, error handling)
- JWT-based authentication
- Goroutines for background tasks
- In-memory data store with repository pattern
- Dependency injection pattern
- Unit tests
├── cmd/
│ └── api/ # Application entry point
├── internal/ # Private application code
│ ├── handlers/ # HTTP request handlers
│ ├── middleware/ # Custom middleware
│ ├── models/ # Data models
│ ├── repository/ # Data access layer
│ └── services/ # Business logic
├── pkg/ # Public libraries
│ └── auth/ # Authentication utilities
└── configs/ # Configuration files
- Go 1.16 or higher
-
Clone the repository:
git clone https://github.com/yourusername/todo-chi.git cd todo-chi
-
Install dependencies:
go mod tidy
-
Run the application:
go run cmd/api/main.go
-
The API will be available at http://localhost:8080
-
POST /api/auth/register
- Register a new user{ "username": "user", "password": "password" }
-
POST /api/auth/login
- Login and get a JWT token{ "username": "user", "password": "password" }
GET /api/todos
- Get all todosGET /api/todos/{id}
- Get a specific todoPOST /api/todos
- Create a new todo{ "title": "Todo Title", "description": "Todo Description" }
PUT /api/todos/{id}
- Update a todo{ "title": "Updated Title", "description": "Updated Description", "completed": true }
DELETE /api/todos/{id}
- Delete a todoPATCH /api/todos/{id}/toggle
- Toggle todo completion status
Authentication is handled with JWT tokens. To access protected routes:
- Register or login to get a token
- Include the token in the Authorization header for subsequent requests:
Authorization: Bearer YOUR_TOKEN_HERE
Run tests with:
go test ./...
The application uses Chi for routing and middleware chains. Middleware is applied in both global and route-specific contexts.
See how request context is used to pass data between middleware and handlers, particularly for authentication.
Background tasks are handled with goroutines, demonstrating safe concurrent programming.
The project follows principles of clean architecture with clear separation between:
- Handlers (presentation layer)
- Services (business logic)
- Repository (data access)
Components are designed with dependency injection principles for better testability.