{"id":19866052,"url":"https://github.com/rameshsunkara/go-rest-api-example","last_synced_at":"2026-02-26T07:49:05.041Z","repository":{"id":38980707,"uuid":"495596249","full_name":"rameshsunkara/go-rest-api-example","owner":"rameshsunkara","description":"Production-ready Go REST APIs without the enterprise bloat","archived":false,"fork":false,"pushed_at":"2026-01-31T03:55:00.000Z","size":727,"stargazers_count":408,"open_issues_count":0,"forks_count":46,"subscribers_count":4,"default_branch":"main","last_synced_at":"2026-01-31T18:47:05.905Z","etag":null,"topics":["api","api-framework","api-rest","boilerplate","design-patterns","docker-compose","enterpriseservices","go","golang","golangci-lint","mongodb","owasp","production","rest-apis"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rameshsunkara.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2022-05-23T22:47:24.000Z","updated_at":"2026-01-31T03:54:57.000Z","dependencies_parsed_at":"2024-02-25T14:26:38.311Z","dependency_job_id":"ef76fa59-df46-4e2a-84d9-93f51f6218fd","html_url":"https://github.com/rameshsunkara/go-rest-api-example","commit_stats":null,"previous_names":[],"tags_count":6,"template":true,"template_full_name":null,"purl":"pkg:github/rameshsunkara/go-rest-api-example","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rameshsunkara%2Fgo-rest-api-example","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rameshsunkara%2Fgo-rest-api-example/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rameshsunkara%2Fgo-rest-api-example/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rameshsunkara%2Fgo-rest-api-example/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rameshsunkara","download_url":"https://codeload.github.com/rameshsunkara/go-rest-api-example/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rameshsunkara%2Fgo-rest-api-example/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29851893,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-25T22:37:40.667Z","status":"online","status_checked_at":"2026-02-26T02:00:06.774Z","response_time":89,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","api-framework","api-rest","boilerplate","design-patterns","docker-compose","enterpriseservices","go","golang","golangci-lint","mongodb","owasp","production","rest-apis"],"created_at":"2024-11-12T15:24:53.455Z","updated_at":"2026-02-26T07:49:05.036Z","avatar_url":"https://github.com/rameshsunkara.png","language":"Go","readme":"# REST API microservice in Go\n\n[![Build Status](https://github.com/rameshsunkara/go-rest-api-example/actions/workflows/cibuild.yml/badge.svg)](https://github.com/rameshsunkara/go-rest-api-example/actions/workflows/cibuild.yml?query=+branch%3Amain)\n[![Go Report Card](https://goreportcard.com/badge/github.com/rameshsunkara/go-rest-api-example)](https://goreportcard.com/report/github.com/rameshsunkara/go-rest-api-example)\n[![codecov](https://codecov.io/gh/rameshsunkara/go-rest-api-example/branch/main/graph/badge.svg)](https://app.codecov.io/gh/rameshsunkara/go-rest-api-example)\n[![Go Version](https://img.shields.io/badge/Go-1.25-00ADD8?logo=go)](https://go.dev/)\n\n\u003e A production-ready REST API boilerplate built with Go, featuring MongoDB integration, comprehensive middleware, flight recorder tracing, and modern development practices.\n\n![Go REST Api](go-rest-api.svg)\n\n## ✨ Highlights\n\n- 🚀 **Production-Ready**: Graceful shutdown, health checks, structured logging\n- 🔒 **Security-First**: OWASP compliant, multi-tier auth, security headers\n- 📊 **Observability**: Flight recorder tracing, Prometheus metrics, pprof profiling\n- 🧪 **Test Coverage**: 70%+ coverage threshold with parallel testing\n- 🐳 **Docker-Ready**: Multi-stage builds with BuildKit optimization\n- 📝 **Well-Documented**: OpenAPI 3 specification with Postman collection\n\n## 🚀 Quick Start\n\n```bash\n# Clone and start\ngit clone https://github.com/rameshsunkara/go-rest-api-example.git\ncd go-rest-api-example\nmake start\n\n# Your API is now running at http://localhost:8080\ncurl http://localhost:8080/healthz\n```\n\n## 📋 Table of Contents\n\n- [Features](#-key-features)\n- [Architecture](#️-architecture)\n- [Getting Started](#-getting-started)\n- [Available Commands](#-available-commands)\n- [Tools \u0026 Stack](#-tools--stack)\n- [Contributing](#contribute)\n\n## 🎯 Key Features\n\n### API Features\n\n1. **OWASP Compliant Open API 3 Specification**: Refer to [OpenApi-v1.yaml](./OpenApi-v1.yaml) for details.\n2. **Production-Ready Health Checks**:\n   - `/healthz` endpoint with proper HTTP status codes (204/424)\n   - Database connectivity validation\n   - Dependency health monitoring\n3. **Comprehensive Middleware Stack**:\n   - **Request Logging**: Structured logging with request correlation\n   - **Authentication**: Multi-tier auth (external/internal APIs)\n   - **Request ID Tracing**: End-to-end request tracking\n   - **Panic Recovery**: Graceful error handling and recovery\n   - **Security Headers**: OWASP-compliant security header injection\n   - **Query Validation**: Input validation and sanitization\n   - **Compression**: Automatic response compression (gzip)\n4. **Flight Recorder Integration**: Automatic trace capture for slow requests using Go 1.25's built-in flight recorder.\n5. **Standardized Error Handling**: Consistent error response format across all endpoints\n6. **API Versioning**: URL-based versioning with backward compatibility\n7. **Internal vs External APIs**: Separate authentication and access controls\n8. **Model Separation**: Clear distinction between internal and external data representations\n\n### Go Application Features\n\n1. **Configuration Management**: Environment-based configuration with validation\n2. **Graceful Shutdown**: Proper signal handling with resource cleanup and connection draining\n3. **Production-Ready MongoDB Integration**:\n   - Connection pooling and health checks\n   - Functional options pattern for flexible configuration\n   - SRV and replica set support\n   - Credential management via sidecar files\n   - Query logging for debugging\n4. **Comprehensive Health Checks**: `/healthz` endpoint with database connectivity validation\n5. **Structured Logging**: Zero-allocation JSON logging with request tracing\n6. **Secrets Management**: Secure credential loading from sidecar files\n7. **Effective Mocking**: Interface-based design enabling comprehensive unit testing\n8. **Database Indexing**: Automatic index creation for optimal query performance\n9. **Idiomatic Go Architecture**: Clean separation of concerns with dependency injection\n10. **Parallel Testing**: Race condition detection with atomic coverage reporting\n11. **Context-Aware Operations**: Proper context propagation for cancellation and timeouts\n12. **Resource Management**: Automatic cleanup of connections and resources\n\n### Tooling\n\n1. **Dockerized Environment**: Facilitates service deployment using DOCKER_BUILDKIT.\n2. **Makefile**: Automates common tasks for developers.\n3. **GitHub Actions**: Automates building, testing, code coverage reporting, and enforces the required test coverage threshold.\n4. **Multi-Stage Docker Build**: Accelerates build processes.\n\n## 🏗️ Architecture\n\n### 📁 Folder Structure\n\n```text\ngo-rest-api-example/\n├── main.go\n├── internal/           # Private application code\n│   ├── config/         # Configuration management\n│   ├── db/             # Database repositories and data access\n│   ├── errors/         # Application error definitions\n│   ├── handlers/       # HTTP request handlers\n│   ├── middleware/     # HTTP middleware components\n│   ├── models/         # Domain models and data structures\n│   ├── server/         # HTTP server setup and lifecycle\n│   ├── utilities/      # Internal utilities\n│   └── mockData/       # Test and development data\n├── pkg/                # Public packages (can be imported)\n│   ├── logger/         # Structured logging utilities\n│   └── mongodb/        # MongoDB connection management\n├── localDevelopment/   # Local dev setup (DB init scripts, etc.)\n├── Makefile            # Development automation\n├── Dockerfile          # Container image definition\n├── docker-compose.yaml # Local development services\n├── OpenApi-v1.yaml     # API specification\n└── OpenApi-v1.postman_collection.json\n```\n\n### ➡️ Control Flow\n\n```mermaid\nflowchart LR\n   Request e1@==\u003e Server\n   e1@{ animate: true }\n   Server e2@==\u003e Router\n   e2@{ animate: true }\n   M@{ shape: processes, label: \"Middlewares\" }\n   Router e3@==\u003e M\n   e3@{ animate: true }\n   C@{ shape: processes, label: \"Handlers\" }\n   M e4@==\u003e C\n   e4@{ animate: true }\n   R@{ shape: processes, label: \"Repos(DAO)\" }\n   C e5@==\u003e R\n   e5@{ animate: true }\n   id1[(Database)]\n   R e6@==\u003e id1\n   e6@{ animate: true }\n```\n\n1. **Request**: Server receives the incoming request.\n2. **Server**: Server processes the request and forwards it to the router.\n3. **Router**: Router directs the request to the appropriate middleware(s).\n4. **Middlewares**: The middlewares handle various tasks such as logging, authentication, security headers, tracing etc.,\n5. **Handlers**: The request is passed to the appropriate handler, which validates the request and forwards it to the repository layer.\n6. **Repos(DAO)**: The repository layer communicates with the database to perform CRUD operations.\n\n## 🚀 Getting Started\n\n### Prerequisites\n\n- Docker and [Docker Compose](https://docs.docker.com/compose/install/)\n- Make\n\n### Start the Application\n\n```bash\ngit clone https://github.com/rameshsunkara/go-rest-api-example.git\ncd go-rest-api-example\nmake start\n```\n\nYour API is now running at `http://localhost:8080`\n\n**Try it out:**\n```bash\ncurl http://localhost:8080/api/v1/healthz\ncurl http://localhost:8080/api/v1/orders\n```\n\n## 📟 Available Commands\n\n### Essential Commands\n\n```makefile\nstart                          Start all necessary services and API server\nrun                            Run the API server (requires dependencies running)\nsetup                          Start only dependencies (MongoDB)\ntest                           Run tests with coverage\n```\n\n### Development Commands\n\n```makefile\nlint                           Run the linter\nlint-fix                       Run the linter and fix issues\ntrace                          Analyze a trace file (usage: make trace TRACE_FILE=./traces/slow-request-GET-orders-1234567890.trace)\nclean                          Clean all Docker resources (keeps database data)\nclean-all                      Clean all Docker resources including volumes (removes database data)\ncoverage                       Generate and display the code coverage report\n```\n\n### CI/CD Commands\n\n```makefile\nbuild                          Build the API server binary\nci-coverage                    Check if test coverage meets the threshold\nformat                         Format Go code\nversion                        Display the current version of the API server\n```\n\n### Docker Commands\n\n```makefile\ndocker-build                   Build the Docker image\ndocker-start                   Build and run the Docker container\ndocker-clean                   Clean all Docker resources\n```\n\n\u003e 💡 **Tip**: Run `make help` to see all available commands.\n\n### Additional Prerequisites for Development\n\n- [golangci-lint](https://golangci-lint.run/welcome/install/#local-installation) - For linting\n- [docker-buildx](https://docs.docker.com/buildx/working-with-buildx/) - For multi-platform builds\n\n## 🛠 Tools \u0026 Stack\n\n| Category | Technology |\n|----------|-----------|\n| **Web Framework** | [Gin](https://github.com/gin-gonic/gin) |\n| **Logging** | [zerolog](https://github.com/rs/zerolog) |\n| **Database** | [MongoDB](https://www.mongodb.com/) |\n| **Container** | [Docker](https://www.docker.com/) + BuildKit |\n| **Tracing** | Go 1.25 Flight Recorder |\n| **Profiling** | [pprof](https://golang.org/pkg/net/http/pprof/) |\n\n## 📚 Additional Resources\n\n### Roadmap\n\n\u003cdetails\u003e\n\u003csummary\u003eClick to expand planned features\u003c/summary\u003e\n\n- [ ] Add comprehensive API documentation with examples\n- [ ] Implement database migration system\n- [ ] Add distributed tracing (OpenTelemetry integration)\n- [ ] Add metrics collection and Prometheus integration\n- [ ] Add git hooks for pre-commit and pre-push\n- [ ] Implement all remaining OWASP security checks\n\n\u003c/details\u003e\n\n### Nice to Have\n\n\u003cdetails\u003e\n\u003csummary\u003eFuture enhancements\u003c/summary\u003e\n\n- **Enhanced Data Models**: Add validation, relationships, and business logic\n- **Cloud Deployment**: Kubernetes manifests and Helm charts\n- **Advanced Monitoring**: APM integration, alerting, and dashboards\n- **Caching Layer**: Redis integration for performance optimization\n- **Multi-database Support**: PostgreSQL, CockroachDB adapters\n- **Performance Testing**: Load testing scenarios and benchmarks\n\n\u003c/details\u003e\n\n### References\n\n- [gin-boilerplate](https://github.com/Massad/gin-boilerplate)\n- [go-rest-api](https://github.com/qiangxue/go-rest-api)\n- [go-base](https://github.com/dhax/go-base)\n\n## 🤝 Contribute\n\nContributions are welcome! Here's how you can help:\n\n- 🐛 **Found a bug?** [Open an issue](https://github.com/rameshsunkara/go-rest-api-example/issues)\n- 💡 **Have a feature idea?** [Start a discussion](https://github.com/rameshsunkara/go-rest-api-example/discussions)\n- 🔧 **Want to contribute code?** Fork the repo and submit a PR\n\n## 📖 Why This Project?\n\nAfter years of developing Full Stack applications using ReactJS and JVM-based languages, I found existing Go boilerplates were either too opinionated or too minimal. \n\nIn the age of Copilot and Cursor, you might wonder: \"Why another REST API boilerplate?\"\nFair question. But this isn't just another \"Hello World\" REST API—this is about building for **enterprise**.\n\n### What Makes It Different\n\nThis project strikes a balance between simplicity and production-readiness:\n\n✅ **Just Right**: Not too bloated, not too minimal  \n✅ **Best Practices**: Follows Go idioms and patterns  \n✅ **Production-Tested**: Battle-tested patterns from real-world applications  \n✅ **Flexible**: Easy to customize for your specific needs  \n\n### Beyond Performance: Building for Enterprise\n\nIn enterprise software, it's not always about raw performance alone. It's about building systems that:\n\n- **Scale with your team**: Code that's readable by engineers at all skill levels, not just the most experienced\n- **Enable safe changes**: Clear boundaries between components so changes don't cascade unexpectedly, with each layer independently testable\n- **Prevent bad practices**: Built-in guardrails that guide developers toward correct patterns\n- **Simplify troubleshooting**: When issues hit production (and they will), you can diagnose them quickly\n- **Measure what matters**: Easy performance profiling and metrics collection without major refactoring\n- **Support evolution**: Adding new features doesn't require rewriting existing code\n- **Delight developers**: New team members become productive in minutes, not days\n\n### What This Is NOT\n\n❌ A complete e-commerce solution\n❌ A framework that does everything for you\n❌ The only way to structure a Go API\n\n**This is a solid foundation to build upon.** Take what you need, leave what you don't.\n\n---\n\n\u003cdiv align=\"center\"\u003e\n\n**⭐ If you find this helpful, please consider giving it a star! ⭐**\n\n\u003c/div\u003e","funding_links":[],"categories":["Go"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frameshsunkara%2Fgo-rest-api-example","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frameshsunkara%2Fgo-rest-api-example","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frameshsunkara%2Fgo-rest-api-example/lists"}