A robust, modular food ordering backend and supporting library, designed for extensibility, performance, and developer productivity. This project features a RESTful API for product listing, cart management, and order processing, as well as a shared Go library for logging, configuration, and integrations. The platform includes an optimized coupon processing system capable of handling large files (1-2 GB) with parallel processing and resume functionality.
- βοΈ Microservices with clear domain boundaries
- π REST APIs with versioning
- π§ͺ Unit, integration, and contract tests
- π³ Docker-based local dev environment
- ποΈ Mongodb integrations
- π Observability: Logging, Tracing, Metrics
- π Secure config, secrets management, and auth hooks
- π¦ DevTools: Task runners, hot reloads, linters, CI templates
- π Clean project layout (Go idiomatic)
This repository is created as a reference implementation to:
- Demonstrate best practices for building Go microservices
- Highlight developer productivity tools for local and team workflows
- Provide a foundation for production-grade Go backend systems
- Generated Mocks: Automated mock generation using GoMock for all interfaces
- Interface-Based Testing: Clean separation of concerns with interface-based repository design
- Comprehensive Test Coverage: Unit tests for all services with proper mocking patterns
- Human-Readable Tests: Well-structured test cases with clear Given/When/Then patterns
- Mock Validation: Proper expectation verification and error scenario testing
- Interface-Driven Design: MongoDB collections abstracted through interfaces for better testability
- Dependency Injection: Clean dependency management with interface-based mocking
- Type Safety: Strong typing with proper error handling and validation
- Modular Structure: Clear separation between data access and business logic
- High-Performance File Processing: Optimized coupon file processor capable of handling 1-2 GB files with:
- Parallel processing with worker pools (4 concurrent workers)
- Increased batch sizes (5000 items)
- Optimized I/O operations with larger buffers (1MB scanner, 64KB hash buffer)
- Memory-efficient processing with pre-allocated slices
- 3-5x faster processing for large files
- Comprehensive Documentation: All exposed types and functions now have detailed GoDoc comments
- Enhanced Logger Interface: Complete ILogger interface with all public methods documented
- Automated Code Quality: Pre-commit hooks with linting, formatting, and security scanning
- Mock Generation: Automated mock generation for testing with GoMock
- API Documentation: Auto-generated Swagger/OpenAPI documentation
- Resume Functionality: Coupon processing can resume from where it left off after failures
- File Deduplication: MD5 hash-based file tracking prevents duplicate processing
- Graceful Error Recovery: Comprehensive error handling with proper status updates
- Context Cancellation: Support for graceful shutdown and timeout handling
kart-challenge/
βββ backend-challenge/
β βββ library/ # Shared Go library (logger, config, etc.)
β β βββ logger/ # Advanced logging with file rotation and async support
β β β βββ mocks/ # Generated mocks for testing
β β β βββ interface.go # Complete ILogger interface definition
β β βββ config/ # Configuration management with validation
β βββ services/
β β βββ coupons/ # Coupons microservice with optimized file processing
β β β βββ cmd/processor/ # Coupons processor entrypoint
β β β βββ internal/ # Service internals (processor, repository, config)
β β β β βββ repository/ # Interface-based repository with generated mocks
β β β β β βββ mocks/ # Generated mocks for testing
β β β β β βββ interface.go # Collection and CouponRepository interfaces
β β β β βββ processor/ # Optimized file processor with resume capability
β β β βββ data/ # Sample data and test files
β β βββ orderfoodonline/ # Main food ordering service
β β βββ cmd/rest/ # REST API entrypoint and docs
β β βββ internal/ # Service internals (handlers, middlewares, routes, etc.)
β β β βββ service/ # Business logic with comprehensive unit tests
β β β βββ repository/ # Data access layer with generated mocks
β β β βββ http/ # HTTP handlers with proper error handling
β β βββ migrations/ # Database migrations and seeding
β β βββ Dockerfile # Multi-stage build for the service
β βββ Makefile # Root Makefile for orchestration
βββ api/
β βββ openapi.yaml # OpenAPI spec for the API
βββ docker-compose.local.yml # Local dev orchestration
βββ .pre-commit-config.yaml # Pre-commit hooks for Go quality and CI
βββ shell.nix # Nix shell for reproducible dev env
βββ README.md # This file- One-Command Setup:
make startlaunches the entire development environment - Hot Reload-TODO: Automatic code reloading with
airfor instant feedback - Docker Compose: Complete environment with MongoDB, services, and networking
- Nix Shell: Reproducible development environment (optional)
- Pre-commit Hooks: Automated quality gates before commits
- Comprehensive Testing: Unit tests with coverage reporting and generated mocks
- Mock Generation: Automated mock creation for isolated testing with GoMock
- Static Analysis: Security scanning, linting, and code formatting
- Interface Compliance: Automated verification of interface implementations
- Auto-generated Docs: Swagger documentation from code comments
- GoDoc Comments: Comprehensive documentation for all public APIs
- OpenAPI Spec: Machine-readable API specification
- Interactive API: Swagger UI for testing endpoints
- Structured Logging: JSON-formatted logs with configurable levels
- File Rotation: Automatic log file management
- Performance Metrics: Built-in timing and monitoring
- Error Tracking: Detailed error context and stack traces
- Prometheus Metrics: Comprehensive metrics collection with
/metricsendpoint- HTTP request counts, durations, and status codes
- Database query latency and operation counts
- Order processing metrics and business KPIs
- Active database connections monitoring
- Product Listing & Cart API: RESTful endpoints for products, cart, and order management
- Coupon Processing: High-performance file processing with resume capability
- Database Migrations: Automated schema management and data seeding
- Authentication: API key-based authentication middleware
- Advanced Logging: Configurable logging with file rotation, colors, and async support
- Configuration Management: Environment-aware configuration with validation
- Error Handling: Centralized error management and reporting
- Health Checks: Built-in health and version endpoints
- Pre-commit Quality Gates: Lint, format, staticcheck, security scan, and tests
- API Documentation: Swagger/OpenAPI 3.1 docs, auto-generated with
swag - Dockerized: Multi-stage Dockerfiles for efficient builds and minimal runtime images
- Makefile Automation: Common tasks for build, test, docs, and pre-commit
- Mock Generation: Automated test double creation for isolated testing
- Go 1.23+
- Docker
- Make
- Nix (optional) for reproducible environments
- pre-commit (install via pip or your package manager)
# Clone and setup
git clone <your-repo-url>
cd kart-challenge
pre-commit install
# Start everything with one command
make start
# Access the API
curl http://localhost:8080/api/health# Install pre-commit hooks
pre-commit install
# Start services
make start
# Or run individual services
docker compose -f docker-compose.local.yml up --buildstartβ Start all services with Docker Composestopβ Stop all servicesprecommit-orderfoodonlineβ Generate docs/mocks, build, and test orderfoodonlineprecommit-couponsβ Generate docs/mocks, build, and test coupons servicetest-apiβ Run Postman collection tests with default settingstest-api-envβ Run Postman collection tests using environment filetest-api-npxβ Run Postman collection tests using npx (no global install required)test-api-with-keyβ Run Postman collection tests with custom API keyinstall-newmanβ Install Newman CLI tool for Postman testing
depβ Rungo mod tidybuildβ Build Docker imagetestβ Run all Go tests with coveragegenerate-mocksβ Generate GoMock mocksgenerate-docsβ Generate Swagger docsprecommitβ Run all of the above for CI
Configured in .pre-commit-config.yaml:
- Go Build/Format/Lint/Staticcheck β Code quality and style
- Go Test β Automated testing with coverage
- Go Vet β Static analysis for common mistakes
- GoSec β Security vulnerability scanning
- Gitlint β Commit message style enforcement
- Docs/Mocks Generation β Automated documentation and mock creation
make start
# API: http://localhost:8080
# Swagger UI: http://localhost:8080/swagger/index.html
# MongoDB: mongodb://localhost:27017# Start specific service
docker compose -f docker-compose.local.yml up orderfoodonline
docker compose -f docker-compose.local.yml up coupons
# Run tests
make -C backend-challenge/services/orderfoodonline test
make -C backend-challenge/library test
make -C backend-challenge/services/coupons test# The services are configured with air for hot reloading
# Changes to Go files will automatically restart the servicesThe project includes a comprehensive Postman collection for testing all API endpoints. You can run the tests using Newman (Postman's CLI tool).
# Run tests with npx (recommended - no global install required)
make test-api-npx
# Run tests using environment file
make test-api-env
# Run tests with custom API key
make test-api-with-key# Option 1: Use npx (no installation required)
npx newman run "Order Food Online.postman_collection.json" \
--environment "Order Food Online.postman_environment.json"
# Option 2: Install Newman globally
make install-newman
# or manually:
npm install -g newman --unsafe-perm=true
# or with sudo:
sudo npm install -g newman
# Option 3: Install via Homebrew (macOS)
brew install newman
# Run collection with environment file
newman run "Order Food Online.postman_collection.json" \
--environment "Order Food Online.postman_environment.json" \
--reporters cli,json \
--reporter-json-export postman-results.json- CLI Output: Real-time test results in the terminal
- JSON Report: Detailed results saved to
postman-results.json - Coverage: Tests all endpoints including authentication, products, and orders
- Validation: Response time, status codes, and data structure validation
Update Order Food Online.postman_environment.json to customize:
host: API host (default: localhost)port: API port (default: 8080)api_key: Your API key for authenticationfirstProductId: Auto-populated by tests for dependent requests
- OpenAPI Spec:
api/openapi.yaml - Swagger UI: http://localhost:8080/swagger/index.html (when running locally)
- Auto-generated docs:
backend-challenge/services/orderfoodonline/cmd/rest/docs/ - Health Check:
GET /api/health - Version Info:
GET /api/version - Prometheus Metrics:
GET /metrics- Comprehensive application metrics in Prometheus format
- Parallel Processing: 4 concurrent workers for database operations
- Optimized Batching: 5000 items per batch (5x improvement)
- Memory Efficiency: Pre-allocated slices and buffer reuse
- Resume Capability: Continue processing from failure point
- File Deduplication: MD5 hash-based duplicate detection
- Rate Limiting: Built-in request throttling
- CORS Support: Cross-origin resource sharing
- Graceful Shutdown: Proper cleanup and timeout handling
- Connection Pooling: Efficient database connection management
The application exposes comprehensive metrics at /metrics endpoint in Prometheus format for monitoring and alerting.
-
HTTP Metrics
http_requests_total- Total request count by method, endpoint, and status codehttp_request_duration_seconds- Request duration histogram by method and endpoint
-
Database Metrics
database_queries_total- Database operation counts by operation, collection, and statusdatabase_query_duration_seconds- Query duration histogram by operation and collectiondatabase_active_connections- Number of active database connections
-
Business Metrics
order_processing_duration_seconds- Order processing time by statusorders_total- Order counts by status (success, validation_error, etc.)
# View metrics in browser
curl http://localhost:8080/metrics
# Scrape with Prometheus
# Add to prometheus.yml:
scrape_configs:
- job_name: 'orderfoodonline'
static_configs:
- targets: ['localhost:8080']
metrics_path: '/metrics'
# Monitor specific metrics
curl http://localhost:8080/metrics | grep http_requests_total
curl http://localhost:8080/metrics | grep database_query_duration_seconds- Grafana Dashboards: Create custom dashboards for business and technical metrics
- Alerting: Set up alerts for high error rates, slow queries, or business anomalies
- SLA Monitoring: Track API response times and availability
- Capacity Planning: Monitor database connection usage and query performance
- Interface-Based Design: All dependencies are abstracted through interfaces
- Generated Mocks: Automated mock generation using GoMock for consistent testing
- Comprehensive Coverage: Tests for all public methods and error scenarios
- Human-Readable Tests: Clear Given/When/Then structure with descriptive test names
- Mock Validation: Proper expectation verification and cleanup
func TestService_Method_Success(t *testing.T) {
// Given: Setup with mocked dependencies
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockRepo := mocks.NewMockRepository(ctrl)
// When: Execute the method under test
result, err := service.Method(ctx, input)
// Then: Verify expectations and assertions
require.NoError(t, err)
assert.Equal(t, expected, result)
}# Generate mocks for interfaces
make generate-mocks
# Mocks are automatically generated in mocks/ directories
# and used in unit tests for isolated testing- Create new service under
backend-challenge/services/ - Follow the established structure (cmd/, internal/, Dockerfile)
- Define interfaces for dependencies and generate mocks
- Update root Makefile with new targets
- Add to docker-compose.local.yml
- Add to
backend-challenge/library/ - Include comprehensive tests and documentation
- Update go.mod dependencies
- Generate mocks for any new interfaces
- Add migration files to
migrations/directory - Follow the existing naming convention (0001_, 0002_, etc.)
- Include both schema changes and seed data
- Define the method in the interface
- Implement in the concrete repository
- Generate mocks:
make generate-mocks - Write comprehensive unit tests with proper mocking
- Port conflicts: Ensure ports 8080 and 27017 are available
- Permission issues: Run
chmod +xon shell scripts if needed - Docker issues: Ensure Docker daemon is running
- Mock generation: Run
make generate-mocksif mocks are outdated
- Use
make stop && make startto restart all services - Check logs with
docker compose logs -f service-name - Run tests with coverage:
make -C backend-challenge/services/orderfoodonline test - Regenerate mocks after interface changes:
make generate-mocks
MIT or as specified in this repository.
- Fork the repository
- Create a feature branch
- Make your changes
- Run
pre-commit run --all-filesto ensure quality - Submit a pull request
If you have any questions or want to contribute, please open an issue or pull request!