A complete RESTful Todo List API built with Go, Gin framework, and MongoDB. This project is a Go implementation of the jstodolist project.
-
Authentication & Authorization
- JWT-based authentication with refresh tokens
- User registration and login
- Secure logout mechanism
- Token refresh for long-term sessions
- Protected routes
-
Task Management
- CRUD operations for tasks (Create, Read, Update, Delete)
- Filtering tasks by status, priority
- Sorting by various fields
- Pagination support
-
Database
- MongoDB integration with official Go driver
- Proper data validation
- Effective error handling
-
API Documentation
- Swagger UI at
/api-docs
- Complete API specifications
- Swagger UI at
-
Logging System
- Custom file and console logging
- Request logging with method, status code, latency, IP
- Different log levels (DEBUG, INFO, WARNING, ERROR, SUCCESS)
- Environment-aware logging (debug/release mode)
-
Development
- Environment configuration (.env)
- Development and Production modes
- CORS support
- Proper error handling
- Go - Programming language
- Gin - Web framework
- MongoDB - Database
- JWT - Authentication
- Swagger - API documentation
- Go 1.21 or later
- MongoDB (local or remote)
-
Clone the repository
git clone https://github.com/yourusername/gotodolist.git cd gotodolist
-
Install dependencies
go mod tidy
-
Configure environment
Create a
.env
file in the root directory with the following variables:MONGO_URI=mongodb://localhost:27017 DB_NAME=todolist PORT=8080 GIN_MODE=debug # or 'release' for production CORS_ORIGIN=* JWT_SECRET=your-secret-key JWT_EXPIRE=24h LOG_FILE=logs/app.log
go run main.go
- Set
GIN_MODE=release
in your.env
file or environment - Build and run:
go build ./gotodolist
The API will be available at http://localhost:8080
(or the PORT you specified).
API documentation is available via Swagger UI at /api-docs
when the application is running.
The application includes a comprehensive logging system that works differently based on the current environment:
- DEBUG: Detailed information, typically of interest only when diagnosing problems
- INFO: Confirmation that things are working as expected
- WARNING: Indication that something unexpected happened, but the application is still working
- ERROR: Due to a more serious problem, the application couldn't perform some function
- SUCCESS: Successful completion of an important operation
Logs are formatted as:
[TIMESTAMP] [LEVEL] [FILE:LINE] MESSAGE
Example:
[2025-01-15 14:30:45] [INFO] [main.go:42] Server running on port 8080
All HTTP requests are automatically logged with:
- HTTP method
- Status code
- Response time (latency)
- Client IP
- Request path
- User agent
In your .env
file, set the path for log files:
LOG_FILE=logs/app.log
- In development mode (
GIN_MODE=debug
), logs are written to both console and file - In production mode (
GIN_MODE=release
), logs are written only to file to optimize performance
Method | Endpoint | Description | Authentication |
---|---|---|---|
POST | /auth/register | Register a new user | No |
POST | /auth/login | User login | No |
POST | /auth/refresh-token | Refresh access token | No |
POST | /auth/logout | Logout and invalidate refresh token | Yes |
GET | /auth/me | Get user info | Yes |
Method | Endpoint | Description | Authentication |
---|---|---|---|
GET | /tasks | Get all tasks with filters | Yes |
GET | /tasks/:id | Get a specific task | Yes |
POST | /tasks | Create a new task | Yes |
PUT | /tasks/:id | Update a task | Yes |
DELETE | /tasks/:id | Delete a task | Yes |
Method | Endpoint | Description | Authentication |
---|---|---|---|
GET | /health | API health check | No |
GET | /api-docs | API documentation | No |
type Task struct {
ID primitive.ObjectID `bson:"_id,omitempty" json:"id"`
Title string `bson:"title" json:"title" binding:"required"`
Description string `bson:"description,omitempty" json:"description"`
Completed bool `bson:"completed" json:"completed"`
DueDate *time.Time `bson:"dueDate,omitempty" json:"dueDate"`
Priority string `bson:"priority" json:"priority"`
User primitive.ObjectID `bson:"user" json:"user"`
CreatedAt time.Time `bson:"createdAt" json:"createdAt"`
UpdatedAt time.Time `bson:"updatedAt" json:"updatedAt"`
}
Parameter | Type | Description | Example |
---|---|---|---|
completed | boolean | Filter by completion status | ?completed=true |
priority | string | Filter by priority (low/medium/high) | ?priority=high |
sort | string | Field to sort by | ?sort=createdAt |
sortDir | string | Sort direction (asc/desc) | ?sortDir=desc |
page | integer | Page number for pagination | ?page=2 |
limit | integer | Number of items per page | ?limit=20 |
Combined example: /tasks?completed=false&priority=high&sort=dueDate&sortDir=asc&page=1&limit=10
This API uses JWT (JSON Web Tokens) for authentication with a refresh token system for improved security.
- Short-lived tokens (24h by default, configurable via JWT_EXPIRE)
- Used for authenticating API requests
- Must be included in the Authorization header:
Authorization: Bearer <your_token>
- Long-lived tokens (7 days)
- Used to obtain new access tokens when they expire
- Securely stored in the database (hashed, not in raw form)
- Can be invalidated by user logout
- Login/Register: User receives both access and refresh tokens
- API Requests: Access token is used for authentication
- Token Expiry: When access token expires, use refresh token to get a new pair
- Logout: Invalidates the refresh token, requiring a new login
curl -X POST http://localhost:8080/auth/register \
-H "Content-Type: application/json" \
-d '{
"username": "johndoe",
"email": "john@example.com",
"password": "password123"
}'
curl -X POST http://localhost:8080/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "john@example.com",
"password": "password123"
}'
curl -X POST http://localhost:8080/auth/refresh-token \
-H "Content-Type: application/json" \
-d '{
"refreshToken": "your-refresh-token-here"
}'
curl -X POST http://localhost:8080/auth/logout \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
curl -X POST http://localhost:8080/tasks \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-d '{
"title": "Learn Go",
"description": "Study Go programming basics",
"priority": "high",
"dueDate": "2023-12-31T23:59:59Z"
}'
curl http://localhost:8080/tasks \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
curl -X PUT http://localhost:8080/tasks/task_id_here \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-d '{
"completed": true
}'
curl -X DELETE http://localhost:8080/tasks/task_id_here \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
gotodolist/
βββ main.go # Application entry point
βββ go.mod # Go module definition
βββ go.sum # Go module checksums
βββ .env # Environment variables
βββ .env.example # Example environment variables
βββ swagger.yaml # API documentation
βββ controllers/ # Request handlers
β βββ auth_controller.go
β βββ task_controller.go
βββ models/ # Data models
β βββ task.go
β βββ user.go
βββ routes/ # API routes
β βββ auth_routes.go
β βββ task_routes.go
βββ middleware/ # Middleware components
β βββ auth.go
β βββ logger.go # Logging middleware
β βββ swagger.go
βββ configs/ # Configuration code
β βββ db.go
βββ utils/ # Utility functions
β βββ env.go
β βββ http.go
β βββ token.go # Token management utilities
β βββ logger.go # Logging utilities
βββ logs/ # Log files directory
βββ app.log # Application logs
This project is licensed under the MIT License - see the LICENSE file for details.