A RESTful API built with Go and Fiber following Hexagonal Architecture (Ports & Adapters pattern) using GORM for PostgreSQL database operations.
This project implements Hexagonal Architecture to separate business logic from external concerns:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β cmd/api/ β
β Application Entry Point β
β β’ Bootstrap β
β β’ Configuration β
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββ
β application/ β
β βββββββββββββββββββ βββββββββββββββββββ ββββββββββββββββ β
β β usecases/ β β di/ β β shared/ β β
β β β β β β β β
β β Business Logic β β Dependency β β Response β β
β β Orchestration β β Injection β β Helper β β
β β Coordination β β Management β β Utils β β
β βββββββββββββββββββ βββββββββββββββββββ ββββββββββββββββ β
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββ
β adapters/ β
β βββββββββββββββββββ βββββββββββββββββββ ββββββββββββββββ β
β β handler/http β β repository β β infrastructureβ β
β β β β β β β β
β β HTTP Handlers β β PostgreSQL β β Auth, DB β β
β β Middleware β β GORM Models β β Logging β β
β β Router β β Data Mapping β β Services β β
β β DTOs/Requests β β Mappers β β Storage β β
β βββββββββββββββββββ βββββββββββββββββββ ββββββββββββββββ β
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββ
β core/ β
β βββββββββββββββββββ βββββββββββββββββββ β
β β domain/ β β ports/ β β
β β β β β β
β β Entities β β Interfaces β β
β β Business Rulesβ β (Ports) β β
β β Value Objects β β Contracts β β
β β Enums β β Definitions β β
β βββββββββββββββββββ βββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
musi-be/
βββ cmd/api/ # Application entry point
βββ internal/
β βββ adapters/ # Infrastructure Layer
β β βββ handler/http/ # HTTP handlers, middleware, and routes
β β βββ infrastructure/ # External services (auth, database, excel)
β β βββ repository/postgres/ # PostgreSQL implementations
β βββ application/ # Application Layer
β β βββ usecases/ # Business logic orchestration
β β βββ di/ # Dependency injection container
β β βββ shared/ # Shared utilities (response helpers, utils)
β βββ core/ # Pure Domain Layer
β β βββ domain/ # Business entities and rules
β β βββ ports/ # Interface definitions (Ports)
β βββ config/ # Configuration management
βββ migrations/ # Database migrations
βββ docs/ # API documentation (Postman collection)
βββ scripts/ # Utility scripts
βββ .env.example # Environment variables template
βββ .gitignore # Git ignore rules
βββ Makefile # Build and development tasks
βββ README.md # This file
- JWT-based authentication with HTTP-only cookies
- Role-based access control (Admin, Teacher, Student)
- Password hashing with bcrypt
- Refresh token support
- Secure password validation
- Complete CRUD operations for users
- User activation/deactivation
- Password change functionality
- Role assignment and management
- Enhanced pagination support with configurable page sizes
- Search functionality to filter users by name and email
- Separate endpoints for listing students and teachers
- Class entity management with full business logic validation
- Enhanced pagination support with configurable page sizes
- Search functionality to filter classes by name
- Individual class retrieval by ID
- Role-based access control (Admin/Teacher only)
- Educational data modeling with clean architecture patterns
- Complete exam lifecycle management (Not Yet Started, On Going, Completed)
- Exam creation with subject categorization
- Question management with image support
- Multiple choice and essay question types
- Time-based question scheduling
- Conditional pagination with
is_paginationparameter - Enhanced search functionality to filter exams by title and description
- Role-based exam access and management
- Teacher assignment to exams
- Exam session management for students
- Improved student exam submission with proper PG/essay question handling
- Enhanced result management with search and pagination
- Excel export functionality for exam results by exam or student
- Comprehensive exam result analytics and reporting
- Individual question creation and management
- Support for image attachments
- Multiple choice (PG) and descriptive questions
- Point-based question valuation
- Time-controlled question availability
- Conditional pagination with
is_paginationparameter - Search functionality to filter questions by text content
- Question-to-exam association
- File upload support for question content
- Excel-based bulk data import with comprehensive validation
- Support for all entities: classes, students, teachers, exams, and questions
- Context-aware uploads: Upload students to specific classes, questions to specific exams
- Template system: Download Excel templates for each entity type
- Detailed error reporting: Row-level error tracking with field-specific validation
- Batch processing: Efficient handling of large datasets with progress tracking
- Structured responses: Comprehensive upload statistics and success/failure counts
- Loose Coupling: Business logic independent of external services
- Easy Testing: Each layer can be tested in isolation
- Maintainability: Clear separation of concerns
- Scalability: Easy to add new features or change implementations
- Type Safety: Strong typing with Go interfaces
- Dependency Injection: Clean DI container for better testability
- Consistent API response format with BaseResponse
- Structured error handling
- Enhanced pagination support with configurable limits and offsets
- Search functionality across most listing endpoints
- Conditional pagination for flexible data retrieval
- Success/error status tracking
- Universal Search: Most listing endpoints now support search via
qparameter - Flexible Pagination: Configurable page sizes (max 100) with proper offset calculation
- Conditional Pagination:
is_paginationparameter allows toggling between paginated and full result sets - Smart Filtering: Role-based and context-aware filtering capabilities
- Performance Optimized: Efficient database queries with proper indexing support
- Language: Go 1.21+
- Web Framework: Fiber v2
- Database: PostgreSQL
- ORM: GORM v2
- Authentication: JWT (golang-jwt/jwt/v5)
- Password Hashing: bcrypt
- Logging: Zap (structured logging)
- Configuration: Environment-based
- Architecture: Hexagonal (Ports & Adapters)
- Dependency Injection: Custom DI container
- Database Migrations: SQL-based
- Excel Processing: Excelize for bulk uploads
- File Processing: Multipart file upload support
- Docker: Containerization support with Docker Compose
- Go 1.21 or higher
- PostgreSQL 12 or higher
- Make (optional, for build scripts)
git clone <repository-url>
cd musi-bego mod tidycp .env.example .env
# Edit .env with your configurationCREATE DATABASE musi_be;# Run migrations (if using migration tool)
# The application also supports auto-migration for development
make migrate-up# Development mode
make run
# Or using go directly
go run cmd/api/main.go
# Build and run
make build
./bin/apiThe API will be available at http://localhost:8080
All API responses follow a consistent format:
{
"success": true,
"message": "Operation completed successfully",
"data": { ... }
}Error responses:
{
"success": false,
"error": "Error description"
}Paginated responses:
{
"success": true,
"message": "Classes retrieved successfully",
"data": [
{
"id": 1,
"name": "Mathematics 101",
"created_at": "2024-01-15T10:30:00Z",
"updated_at": "2024-01-15T10:30:00Z"
},
{
"id": 2,
"name": "Physics 201",
"created_at": "2024-01-16T14:20:00Z",
"updated_at": "2024-01-16T14:20:00Z"
}
],
"metadata": {
"total": 25,
"limit": 10,
"offset": 0,
"has_more": true
}
}# Run all tests
make test
# Run tests with coverage
make test-coverage
# Run specific tests
go test ./internal/core/domain/...
go test ./internal/application/usecases/...
go test ./internal/adapters/repository/...-
Core Layer (
/internal/core/)- Domain: Pure business entities and rules
- Ports: Interface definitions for external dependencies
- β No external framework dependencies
- β Testable in isolation
-
Application Layer (
/internal/application/)- Use Cases: Business logic orchestration
- DI Container: Dependency injection management
- Shared: Application utilities (Response helpers)
- β Depends only on core layer
- β Manages transaction boundaries
-
Infrastructure Layer (
/internal/adapters/)- HTTP: Web framework adapters (Fiber)
- Repository: Database implementations (GORM/PostgreSQL)
- Services: External service implementations (Auth, Logging)
- β Implements core ports
- β Can be easily swapped
- Domain Entity: Create entity in
internal/core/domain/ - Port Interface: Add interface in
internal/core/ports/ - Use Case: Implement business logic in
internal/application/usecases/ - Repository Adapter: Implement in
internal/adapters/repository/postgres/ - HTTP Handler: Add in
internal/adapters/handler/http/ - Routes: Configure in
internal/adapters/handler/http/router/ - DI Container: Wire dependencies in
internal/application/di/container/
The project uses SQL-based migrations:
# Create new migration
make migrate-create name=add_new_table
# Run migrations
make migrate-up
# Rollback migrations
make migrate-downMigration files are stored in /migrations/ directory.
The application uses a custom DI container (internal/application/di/container/):
- Centralized dependency management
- Interface-based programming
- Easy testing with mocks
- Proper resource cleanup
Consistent response handling using internal/application/shared/response/:
- BaseResponse: Standard API response structure
- PaginatedResponse: For paginated data
- Builder pattern: For flexible response creation
- Helper functions: For common scenarios
The application uses structured logging with Zap:
- Development: Human-readable format with timestamps
- Production: JSON format with log levels
- Error Handling: Structured error responses with appropriate HTTP status codes
- Request Logging: HTTP request/response logging
- Performance: Request duration tracking
The application includes Docker support for easy deployment using Docker Compose.
To run the application using Docker:
# Clone the repository
git clone <repository-url>
cd musi-be
# Copy environment file
cp .env.example .env
# Edit .env with your configuration
# Run using Docker (via Makefile)
make run-docker- Multi-stage builds for optimized image size
- Health checks for service monitoring
- Graceful shutdown handling
- Volume mounts for persistent data
- Network isolation for security
- Environment variable configuration
For additional Docker commands, check the Makefile with make help.
Create a .env file based on .env.example:
cp .env.example .env
# Edit .env with your configurationThe .env.example file contains all the required environment variables including:
- Server Configuration: Port, environment mode
- Database Configuration: PostgreSQL connection settings
- JWT Configuration: Authentication token settings
- Logging Configuration: Log levels and output formats
- Minio Configuration: Object storage settings for file uploads
- Rate Limiting Configuration: API rate limiting settings
- CORS Configuration: Cross-origin resource sharing settings
.env files to version control.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes following the architecture principles
- Add tests for new functionality
- Ensure all tests pass (
make test) - Update documentation
- Submit a pull request
- Follow Go standard conventions
- Use meaningful variable and function names
- Keep functions small and focused
- Write comprehensive tests
- Document public functions and interfaces
- Follow hexagonal architecture principles
This project is licensed under the MIT License - see the LICENSE file for details.
For questions and support, please open an issue in the repository.
The API documentation is maintained as a Postman collection in docs/docs.json. This file can be imported directly into Postman for interactive API testing and exploration.
- Authentication & Authorization: JWT-based auth with role-based access control
- User Management: Complete CRUD operations with search and enhanced pagination
- Class Management: Educational class management with search functionality
- Exam Management: Full exam lifecycle with conditional pagination and search
- Question Management: Comprehensive question handling with search and flexible pagination
- Exam Session Management: Enhanced student exam submission with PG/essay support
- Result Management: Advanced result tracking with search, pagination, and review workflows
- Bulk Upload: Excel-based bulk data import for all major entities
- Export Functionality: Excel export for exam results and analytics
- Health Monitoring: System health check endpoints
- Universal Search: Search functionality across users, classes, exams, questions, and results
- Flexible Pagination: Configurable pagination with conditional support for full dataset retrieval
- Smart Filtering: Context-aware and role-based data filtering
- Improved Data Validation: Enhanced request validation for better error handling
- Performance Optimized: Efficient query patterns with proper pagination limits
- Open Postman
- Click "Import" in the top left
- Select the
docs/docs.jsonfile from the project - The collection will be imported with all endpoints organized by feature
- Configure environment variables (
baseUrl,token, etc.) for testing
Most endpoints require JWT authentication. Use the login endpoint to obtain a token, which will be automatically stored in cookies for subsequent requests.
- v1.0.0 - Initial release with hexagonal architecture
- v1.1.0 - Added GORM support and auto-migration
- v1.2.0 - Added dependency injection container
- v1.3.0 - Added response standardization
- v1.4.0 - Improved architecture separation and router structure
- v1.5.0 - Added class management functionality with role-based access control
- v1.6.0 - Added exam management functionality with role-based access control
- v1.7.0 - Added question management with image support and time scheduling
- v1.8.0 - Added bulk upload functionality with Excel processing
- v1.9.0 - Enhanced with class-student and exam-teacher relationships
- v1.10.0 - Added Docker support and graceful shutdown features
- v1.11.0 - Enhanced bulk upload system with comprehensive Excel template support and context-aware uploads
- v1.12.0 - Added exam session management functionality with student exam submission capabilities
- v1.13.0 - Added Excel export functionality for exam results by exam ID and student ID
- v1.14.0 - Major API Enhancement: Added universal search functionality across all listing endpoints with enhanced pagination support and conditional data retrieval
- v1.14.1 - Improved exam session submission with proper PG/essay question handling and enhanced validation
- v1.14.2 - Enhanced result management with search capabilities and improved pagination controls
- v1.14.3 - Updated API documentation with comprehensive parameter descriptions and examples
Built with β€οΈ using Go, Fiber, and Hexagonal Architecture