A production-ready REST API boilerplate built with Go, featuring MongoDB integration, comprehensive middleware, flight recorder tracing, and modern development practices.
- π Production-Ready: Graceful shutdown, health checks, structured logging
- π Security-First: OWASP compliant, multi-tier auth, security headers
- π Observability: Flight recorder tracing, Prometheus metrics, pprof profiling
- π§ͺ Test Coverage: 70%+ coverage threshold with parallel testing
- π³ Docker-Ready: Multi-stage builds with BuildKit optimization
- π Well-Documented: OpenAPI 3 specification with Postman collection
# Clone and start
git clone https://github.com/rameshsunkara/go-rest-api-example.git
cd go-rest-api-example
make start
# Your API is now running at http://localhost:8080
curl http://localhost:8080/healthz- OWASP Compliant Open API 3 Specification: Refer to OpenApi-v1.yaml for details.
- Production-Ready Health Checks:
/healthzendpoint with proper HTTP status codes (204/424)- Database connectivity validation
- Dependency health monitoring
- Comprehensive Middleware Stack:
- Request Logging: Structured logging with request correlation
- Authentication: Multi-tier auth (external/internal APIs)
- Request ID Tracing: End-to-end request tracking
- Panic Recovery: Graceful error handling and recovery
- Security Headers: OWASP-compliant security header injection
- Query Validation: Input validation and sanitization
- Compression: Automatic response compression (gzip)
- Flight Recorder Integration: Automatic trace capture for slow requests using Go 1.25's built-in flight recorder.
- Standardized Error Handling: Consistent error response format across all endpoints
- API Versioning: URL-based versioning with backward compatibility
- Internal vs External APIs: Separate authentication and access controls
- Model Separation: Clear distinction between internal and external data representations
- Configuration Management: Environment-based configuration with validation
- Graceful Shutdown: Proper signal handling with resource cleanup and connection draining
- Production-Ready MongoDB Integration:
- Connection pooling and health checks
- Functional options pattern for flexible configuration
- SRV and replica set support
- Credential management via sidecar files
- Query logging for debugging
- Comprehensive Health Checks:
/healthzendpoint with database connectivity validation - Structured Logging: Zero-allocation JSON logging with request tracing
- Secrets Management: Secure credential loading from sidecar files
- Effective Mocking: Interface-based design enabling comprehensive unit testing
- Database Indexing: Automatic index creation for optimal query performance
- Idiomatic Go Architecture: Clean separation of concerns with dependency injection
- Parallel Testing: Race condition detection with atomic coverage reporting
- Context-Aware Operations: Proper context propagation for cancellation and timeouts
- Resource Management: Automatic cleanup of connections and resources
- Dockerized Environment: Facilitates service deployment using DOCKER_BUILDKIT.
- Makefile: Automates common tasks for developers.
- GitHub Actions: Automates building, testing, code coverage reporting, and enforces the required test coverage threshold.
- Multi-Stage Docker Build: Accelerates build processes.
go-rest-api-example/
βββ main.go
βββ internal/ # Private application code
β βββ config/ # Configuration management
β βββ db/ # Database repositories and data access
β βββ errors/ # Application error definitions
β βββ handlers/ # HTTP request handlers
β βββ middleware/ # HTTP middleware components
β βββ models/ # Domain models and data structures
β βββ server/ # HTTP server setup and lifecycle
β βββ utilities/ # Internal utilities
β βββ mockData/ # Test and development data
βββ pkg/ # Public packages (can be imported)
β βββ logger/ # Structured logging utilities
β βββ mongodb/ # MongoDB connection management
βββ localDevelopment/ # Local dev setup (DB init scripts, etc.)
βββ Makefile # Development automation
βββ Dockerfile # Container image definition
βββ docker-compose.yaml # Local development services
βββ OpenApi-v1.yaml # API specification
βββ OpenApi-v1.postman_collection.json
flowchart LR
Request e1@==> Server
e1@{ animate: true }
Server e2@==> Router
e2@{ animate: true }
M@{ shape: processes, label: "Middlewares" }
Router e3@==> M
e3@{ animate: true }
C@{ shape: processes, label: "Handlers" }
M e4@==> C
e4@{ animate: true }
R@{ shape: processes, label: "Repos(DAO)" }
C e5@==> R
e5@{ animate: true }
id1[(Database)]
R e6@==> id1
e6@{ animate: true }
- Request: Server receives the incoming request.
- Server: Server processes the request and forwards it to the router.
- Router: Router directs the request to the appropriate middleware(s).
- Middlewares: The middlewares handle various tasks such as logging, authentication, security headers, tracing etc.,
- Handlers: The request is passed to the appropriate handler, which validates the request and forwards it to the repository layer.
- Repos(DAO): The repository layer communicates with the database to perform CRUD operations.
- Docker and Docker Compose
- Make
git clone https://github.com/rameshsunkara/go-rest-api-example.git
cd go-rest-api-example
make startYour API is now running at http://localhost:8080
Try it out:
curl http://localhost:8080/api/v1/healthz
curl http://localhost:8080/api/v1/ordersstart Start all necessary services and API server
run Run the API server (requires dependencies running)
setup Start only dependencies (MongoDB)
test Run tests with coveragelint Run the linter
lint-fix Run the linter and fix issues
trace Analyze a trace file (usage: make trace TRACE_FILE=./traces/slow-request-GET-orders-1234567890.trace)
clean Clean all Docker resources (keeps database data)
clean-all Clean all Docker resources including volumes (removes database data)
coverage Generate and display the code coverage reportbuild Build the API server binary
ci-coverage Check if test coverage meets the threshold
format Format Go code
version Display the current version of the API serverdocker-build Build the Docker image
docker-start Build and run the Docker container
docker-clean Clean all Docker resourcesπ‘ Tip: Run
make helpto see all available commands.
- golangci-lint - For linting
- docker-buildx - For multi-platform builds
| Category | Technology |
|---|---|
| Web Framework | Gin |
| Logging | zerolog |
| Database | MongoDB |
| Container | Docker + BuildKit |
| Tracing | Go 1.25 Flight Recorder |
| Profiling | pprof |
Click to expand planned features
- Add comprehensive API documentation with examples
- Implement database migration system
- Add distributed tracing (OpenTelemetry integration)
- Add metrics collection and Prometheus integration
- Add git hooks for pre-commit and pre-push
- Implement all remaining OWASP security checks
Future enhancements
- Enhanced Data Models: Add validation, relationships, and business logic
- Cloud Deployment: Kubernetes manifests and Helm charts
- Advanced Monitoring: APM integration, alerting, and dashboards
- Caching Layer: Redis integration for performance optimization
- Multi-database Support: PostgreSQL, CockroachDB adapters
- Performance Testing: Load testing scenarios and benchmarks
Contributions are welcome! Here's how you can help:
- π Found a bug? Open an issue
- π‘ Have a feature idea? Start a discussion
- π§ Want to contribute code? Fork the repo and submit a PR
After years of developing Full Stack applications using ReactJS and JVM-based languages, I found existing Go boilerplates were either too opinionated or too minimal. This project strikes a balance:
β Just Right: Not too bloated, not too minimal β Best Practices: Follows Go idioms and patterns β Production-Tested: Battle-tested patterns from real-world applications β Flexible: Easy to customize for your specific needs
β A complete e-commerce solution β A framework that does everything for you β The only way to structure a Go API
This is a solid foundation to build upon. Take what you need, leave what you don't.
β If you find this helpful, please consider giving it a star! β