Skip to content

Monolith with Hexagonal Architechture for exam online students, with admin action upload class, exams, questions, answers using excel

Notifications You must be signed in to change notification settings

PickHD/exam-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

85 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Musi BE API - Hexagonal Architecture

A RESTful API built with Go and Fiber following Hexagonal Architecture (Ports & Adapters pattern) using GORM for PostgreSQL database operations.

πŸ—οΈ Architecture Overview

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   β”‚                  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“ Project Structure

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

πŸš€ Features

Authentication & Authorization

  • JWT-based authentication with HTTP-only cookies
  • Role-based access control (Admin, Teacher, Student)
  • Password hashing with bcrypt
  • Refresh token support
  • Secure password validation

User Management

  • 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 Management

  • 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

Exam Management

  • 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_pagination parameter
  • 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

Question Management

  • 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_pagination parameter
  • Search functionality to filter questions by text content
  • Question-to-exam association
  • File upload support for question content

Bulk Upload Management

  • 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

Architecture Benefits

  • 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

Response Standardization

  • 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

Enhanced Search & Pagination Features

  • Universal Search: Most listing endpoints now support search via q parameter
  • Flexible Pagination: Configurable page sizes (max 100) with proper offset calculation
  • Conditional Pagination: is_pagination parameter 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

πŸ› οΈ Tech Stack

  • 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

πŸ“‹ Prerequisites

  • Go 1.21 or higher
  • PostgreSQL 12 or higher
  • Make (optional, for build scripts)

πŸš€ Quick Start

1. Clone the repository

git clone <repository-url>
cd musi-be

2. Install dependencies

go mod tidy

3. Set up environment variables

cp .env.example .env
# Edit .env with your configuration

4. Set up PostgreSQL database

CREATE DATABASE musi_be;

5. Run database migrations

# Run migrations (if using migration tool)
# The application also supports auto-migration for development
make migrate-up

6. Run the application

# Development mode
make run

# Or using go directly
go run cmd/api/main.go

# Build and run
make build
./bin/api

The API will be available at http://localhost:8080

Response Format

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
  }
}

πŸ§ͺ Testing

# 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/...

πŸ”§ Development

Code Organization Principles

Hexagonal Architecture Layers:

  1. Core Layer (/internal/core/)

    • Domain: Pure business entities and rules
    • Ports: Interface definitions for external dependencies
    • βœ… No external framework dependencies
    • βœ… Testable in isolation
  2. 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
  3. 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

Adding New Features

  1. Domain Entity: Create entity in internal/core/domain/
  2. Port Interface: Add interface in internal/core/ports/
  3. Use Case: Implement business logic in internal/application/usecases/
  4. Repository Adapter: Implement in internal/adapters/repository/postgres/
  5. HTTP Handler: Add in internal/adapters/handler/http/
  6. Routes: Configure in internal/adapters/handler/http/router/
  7. DI Container: Wire dependencies in internal/application/di/container/

Database Migrations

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-down

Migration files are stored in /migrations/ directory.

Dependency Injection

The application uses a custom DI container (internal/application/di/container/):

  • Centralized dependency management
  • Interface-based programming
  • Easy testing with mocks
  • Proper resource cleanup

Response Handling

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

πŸ“Š Monitoring & Logging

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

🐳 Docker Support

The application includes Docker support for easy deployment using Docker Compose.

Running with Docker

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

Docker Features

  • 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.

πŸ“ Environment Variables

Create a .env file based on .env.example:

cp .env.example .env
# Edit .env with your configuration

The .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

⚠️ Important: Always use strong, unique secrets for production environments and never commit actual .env files to version control.

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes following the architecture principles
  4. Add tests for new functionality
  5. Ensure all tests pass (make test)
  6. Update documentation
  7. Submit a pull request

Code Style Guidelines

  • 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

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ†˜ Support

For questions and support, please open an issue in the repository.

πŸ“š API Documentation

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.

Key Features Available in the API:

  • 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

Enhanced API Capabilities:

  • 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

Importing to Postman:

  1. Open Postman
  2. Click "Import" in the top left
  3. Select the docs/docs.json file from the project
  4. The collection will be imported with all endpoints organized by feature
  5. Configure environment variables (baseUrl, token, etc.) for testing

Authentication:

Most endpoints require JWT authentication. Use the login endpoint to obtain a token, which will be automatically stored in cookies for subsequent requests.

πŸ”„ Version History

  • 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

About

Monolith with Hexagonal Architechture for exam online students, with admin action upload class, exams, questions, answers using excel

Topics

Resources

Stars

Watchers

Forks

Contributors 2

  •  
  •  

Languages