Skip to content

goodone-dev/go-boilerplate

Repository files navigation

Go Boilerplate

Go Report Card Go Quality Gate Active Development

This Go RESTful API Boilerplate is engineered to provide a robust, scalable, and production-grade foundation for your next web service. It embraces a clean, Domain-Driven Design (DDD) architecture to ensure maintainability and separation of concerns, empowering you to focus on delivering business value instead of wrestling with infrastructure setup.

🌟 Features

  • πŸ—οΈ Clean Architecture: Separates concerns into distinct layers (domain, application, infrastructure, presentation) for a more organized, testable, and maintainable codebase.
  • 🌐 RESTful API: A lightweight and high-performance RESTful API built with Gin, a popular Go web framework. Includes CORS and HTTP Security middleware.
  • πŸ”„ Live Reload: Automatically restart the application when file changes are detected.
  • πŸ—ƒοΈ Multiple Database Support: Supports PostgreSQL, MySQL, and MongoDB. Uses a repository pattern for flexible data management.
  • 🌱 Database Migration & Seeding: Manage your database schema and seed data with simple make commands.
  • ⚑ Multiple Cache Support: Easily connect to Redis or an in-memory cache.
  • 🧩 Dependency Injection: Switch between database or cache implementations without altering business logic.
  • πŸ› οΈ Code Generation: Automatically generate repository, usecase, and delivery handler with a single make generate command.
  • πŸ“ˆ Observability: Observability features include distributed tracing, metrics, and logging.
  • 🏁 Health Check: /health endpoint for liveness and readiness probes.
  • βœ… Request Validation: Validates incoming HTTP requests using struct tags to ensure data integrity.
  • 🧹 Request Sanitization: Sanitizes incoming request data based on struct tags to prevent XSS and other injection attacks.
  • ⏱️ Context Propagation: Manages request lifecycles with Go's context to handle cancellations and timeouts gracefully.
  • πŸ”„ Idempotency Handler: Prevents duplicate requests by using a distributed cache, ensuring an operation is processed only once.
  • 🚦 Rate Limiting: A distributed rate-limiting middleware to protect your API from excessive traffic and abuse.
  • πŸ”Œ Circuit Breaker: Enhances application stability by preventing repeated calls to failing external services.
  • πŸ“¦ Standardized Response: Consistent JSON response format across all API endpoints, making it easier for clients to parse and handle responses uniformly.
  • βœ‰οΈ Email Sending: Includes a mail sender service with support for HTML templates, allowing for easy and dynamic email generation.
  • πŸ•’ Background Job Processing: Efficiently handle long-running or resource-intensive tasks asynchronously, ensuring responsive API performance and better user experience.
  • 🎭 Mock Generation: Easily generate mocks for interfaces using the make mock command, simplifying unit testing.
  • πŸŒ™ Graceful Shutdown: Ensures that the server shuts down gracefully, finishing all in-flight requests and cleaning up resources before exiting.
  • 🐳 Dockerized Environment: Comes with Dockerfile and docker-compose.yml for a consistent and easy-to-set-up local development environment.
  • πŸ”’ Pre-Commit Hooks: Automated git hooks that run code quality checks, including linting, formatting, and security scanning before each commit.
  • πŸ›‘οΈ Quality Gate CI/CD: Automated quality checks in the CI/CD pipeline that enforce code quality standards, test coverage requirements, and security scans before deployment.

πŸ“Œ Project Roadmap - Track our development progress, upcoming features, and planned improvements on our public roadmap.

πŸš€ Getting Started

Prerequisites

1. Installation

Clone the repository:

git clone https://github.com/goodone-dev/go-boilerplate.git
cd go-boilerplate

2. Project Setup

Run the following command to prepare your development environment. This will make all necessary shell scripts executable:

make setup

To see all available make commands and their descriptions, run:

make help

3. Running the Application

You can run the application in two ways:

Option 1: With Docker (Recommended)

This is the easiest way to get started, as it handles all services (database, cache, etc.) for you.

  1. Start the services:

    make up

    This command builds and starts the application, database, and other services. The API by default will be accessible at http://localhost:8080.

  2. Stop the services:

    make down

    This command stops all services.

Option 2: Locally

This method requires you to run the database and other services on your local machine.

  1. Setup environment variables:

    cp .env.example .env

    Update .env with your configuration. For local development, ensure it points to your local database and other services.

  2. Run database migrations:

    make migration_up DRIVER=postgres
  3. (Optional) Seed the database:

    make seeder_up DRIVER=postgres
  4. Run the application:

    make run

    This command will start the Go application. The API will be accessible at http://localhost:8080.

πŸ“‚ Project Structure

This project is structured following the principles of Clean Architecture. The code is organized into distinct layers, promoting separation of concerns, testability, and maintainability. The dependencies flow inwards, from the outer layers (Infrastructure, Presentation) to the inner layers (Application, Domain).

.
β”œβ”€β”€ .dev/                       # Local development tools, scripts, and configurations.
β”‚   └── script/                 # Local development scripts.
β”œβ”€β”€ .github/                    # GitHub-specific configurations including Actions workflows and issue templates.
β”‚   └── workflow/               # GitHub Actions workflows.
β”œβ”€β”€ cmd/                        # Server commands.
β”‚   β”œβ”€β”€ rest/                   # REST API server.
β”‚   β”‚   └── main.go             # Entry point of the application. Initializes and starts the server.
β”‚   └── utils/                  # Utility functions shared across the server.
β”œβ”€β”€ internal/                   # Internal packages.
β”‚   β”œβ”€β”€ application/            # Implements use cases by orchestrating domain logic.
β”‚   β”‚   β”œβ”€β”€ <domain_name>/      # Groups application logic for a specific domain.
β”‚   β”‚   β”‚   β”œβ”€β”€ handler/        # Adapters for handling incoming requests (e.g., HTTP, messaging).
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ rest/       # REST API handlers for the domain.
β”‚   β”‚   β”‚   β”‚   └── worker/     # Background worker handlers.
β”‚   β”‚   β”‚   β”œβ”€β”€ repository/     # Repository implementations for the domain.
β”‚   β”‚   β”‚   └── usecase/        # Business logic and use cases for the domain.
β”‚   β”‚   └── ...
β”‚   β”œβ”€β”€ config/                 # Configuration loading and management.
β”‚   β”œβ”€β”€ domain/                 # Contains core entities and interfaces.
β”‚   β”‚   β”œβ”€β”€ <domain_name>/      # Groups domain logic for a specific business entity.
β”‚   β”‚   β”‚   └── mocks/          # Mocks for domain interfaces.
β”‚   β”‚   └── ...
β”‚   β”œβ”€β”€ infrastructure/         # Provides implementations for external services.
β”‚   β”‚   β”œβ”€β”€ cache/              # Cache implementations (e.g., Redis).
β”‚   β”‚   β”œβ”€β”€ database/           # Database implementations (PostgreSQL, MySQL, MongoDB).
β”‚   β”‚   β”œβ”€β”€ integration/        # Clients for external APIs.
β”‚   β”‚   β”œβ”€β”€ logger/             # Log aggregation implementations.
β”‚   β”‚   β”œβ”€β”€ mail/               # Email sending implementation.
β”‚   β”‚   β”œβ”€β”€ message/            # Message bus/broker implementation.
β”‚   β”‚   β”œβ”€β”€ tracer/             # Distributed tracing implementation.
β”‚   β”‚   └── ...
β”‚   β”œβ”€β”€ presentation/           # Adapters for incoming requests.
β”‚   β”‚   β”œβ”€β”€ rest/               # REST API handlers, router, and middleware.
β”‚   β”‚   β”‚   β”œβ”€β”€ middleware/     # REST API middleware.
β”‚   β”‚   β”‚   └── router/         # REST API router setup.
β”‚   β”‚   └── worker/             # Background worker handlers.
β”‚   β”‚       └── consumer/       # Message consumer handlers.
β”‚   └── utils/                  # Utility functions shared across the application.
β”‚       β”œβ”€β”€ breaker/            # Circuit breaker utilities.
β”‚       β”œβ”€β”€ html/               # HTML template utilities.
β”‚       β”œβ”€β”€ http_client/        # HTTP client utilities.
β”‚       β”œβ”€β”€ http_response/      # HTTP response utilities.
β”‚       β”œβ”€β”€ sanitizer/          # Request sanitizer utilities.
β”‚       β”œβ”€β”€ validator/          # Request validation utilities.
β”‚       └── ...
β”œβ”€β”€ migrations/                 # SQL migration files for managing database schema changes.
β”‚   β”œβ”€β”€ <database_name>/        # Migration files for a specific database.
β”‚   └── ...
β”œβ”€β”€ seeders/                    # SQL seed files for populating the database with initial data.
β”‚   β”œβ”€β”€ <database_name>/        # Seeder files for a specific database.
β”‚   └── ...
β”œβ”€β”€ templates/                  # HTML templates for emails, PDFs, etc.
β”‚   β”œβ”€β”€ email/                  # Email templates.
β”‚   β”œβ”€β”€ pdf/                    # PDF templates.
β”‚   └── ...
β”œβ”€β”€ .env.example                # Example environment variables file.
β”œβ”€β”€ .air.toml                   # Air.toml for local development.
β”œβ”€β”€ .mockery.yml                # Mockery configuration file.
β”œβ”€β”€ .pre-commit-config.yaml     # Pre-commit configuration file.
β”œβ”€β”€ Makefile                    # Makefile with shortcuts for common development commands.
β”œβ”€β”€ Dockerfile                  # Dockerfile for building the application image.
└── docker-compose.yml          # Defines services for the local Docker environment.

πŸ› οΈ Tech Stack

Category Technologies
Framework gin
Database gorm (PostgreSQL, MySQL), mongo-driver (MongoDB)
Cache go-redis
API Client resty
Config viper
Validation validator
Migration golang-migrate
Observability opentelemetry
Email gomail
Circuit Breaker gobreaker
Mocking mockery

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“ License

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

πŸ“§ Contact

Bagus Abdul Kurniawan

About

Go RESTful API Boilerplate with Clean Architecture

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors