Skip to content

openframebox/goinit-layered

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Goinit Layered Architecture Boilerplate

This project provides a robust and scalable boilerplate for building Go applications with a layered architecture. It's designed to offer a clear separation of concerns, making development, testing, and maintenance more efficient.

Features

Core Architecture

  • Layered Architecture: Clear separation of concerns (handlers, services, repositories, infrastructure).
  • Configuration Management: Environment variable loading with sensible defaults using godotenv.
  • Dependency Injection: Container for managing application dependencies.
  • Error Handling: Custom error types for consistent error responses with proper HTTP status codes.

Authentication & Security

  • JWT Authentication: JWT-based authentication with separate issuer and secret configuration.
  • Request ID Middleware: Unique request tracking for correlation across logs.
  • Rate Limiting: Redis-backed rate limiting to prevent abuse (100 requests/minute default).
  • Security Headers: Automatic security headers (X-Content-Type-Options, X-Frame-Options, CSP, etc.).
  • File Upload Validation: File size, type, and sanitization for secure uploads (10MB max, configurable file types).
  • Sensitive Data Sanitization: Automatic redaction of passwords, tokens, and secrets from logs.

Database & Persistence

  • Database Integration: MySQL/PostgreSQL compatible setup with GORM.
  • Connection Pool Management: Configurable connection pooling (max idle, max open, connection lifetime).
  • Migration Support: Built-in database migration system.
  • Charset Configuration: Configurable database charset (default: utf8mb4).

Infrastructure Services

  • Email Service: Configurable email sending with customizable from address.
  • Queue System: Redis-backed queue for asynchronous task processing.
  • Cache System: Redis-backed cache for frequently accessed data.
  • Storage: Local disk and S3-compatible object storage with path-style configuration.
  • Logging: Structured logging with configurable levels, daily rotation, and dual output (console + file).

API Features

  • API Versioning: Versioned API endpoints with /api/v1 prefix.
  • Data Transfer Objects (DTOs): Validated structures for API request/response payloads.
  • Graceful Shutdown: Proper HTTP server shutdown handling for in-flight requests.
  • CORS Support: Configurable CORS with security warnings for production.

Event System

  • Event Dispatcher: In-application event system for decoupled logic.
  • Async Listeners: Background event processing with queue integration.
  • HTTP Request Events: Automatic request logging with sanitized payloads.

Middleware

  • Authentication Middleware: JWT token validation with safe type assertions.
  • Request ID Middleware: Adds unique identifiers to every request.
  • Rate Limiting Middleware: Prevents API abuse with Redis-backed counters.
  • Security Headers Middleware: Adds essential security headers to all responses.
  • CORS Middleware: Cross-origin resource sharing support.

Code Quality

  • Constants Management: Centralized constants for magic numbers and timeouts.
  • Type-Safe Operations: Proper nil checks and safe type assertions throughout.
  • Structured Logging: WithFields pattern for better log analysis.

Architecture

The project follows a layered architecture pattern, typically structured as follows:

  • cmd/: Contains the main application entry point.
  • internal/: Houses the core application logic, divided into:
    • config/: Application configuration loaded from environment variables.
    • container/: Dependency injection container.
    • customerror/: Custom error definitions.
    • dto/: Data Transfer Objects for API requests and responses.
    • entity/: Domain entities/models.
    • event/: Event definitions and listeners.
    • handler/: HTTP request handlers (controllers).
    • helper/: Utility functions (e.g., response formatting, security).
    • infrastructure/: External concerns like database, logger, email, queue, authenticator, validator.
    • middleware/: HTTP middleware.
    • queue/: Queue job definitions.
    • repository/: Data access layer for interacting with entities.
    • service/: Business logic layer.

Getting Started

Prerequisites

  • Go (version 1.20 or higher recommended)
  • Docker (for local database, Redis, etc.)

Installation

  1. Clone the repository:

    git clone https://github.com/openframebox/goinit-layered.git
    cd goinit-layered
  2. Copy environment variables:

    cp .env.example .env
    # Edit .env file with your specific configurations
  3. Install dependencies:

    go mod tidy

Running the Application

  1. Start Docker services (e.g., database, Redis): You might need a docker-compose.yml file to easily spin up your dependencies. An example could look like this:

    # docker-compose.yml (example)
    version: '3.8'
    services:
      db:
        image: mysql:8.0
        environment:
          MYSQL_ROOT_PASSWORD: root_password
          MYSQL_DATABASE: mymodule
        ports:
          - "3306:3306"
      redis:
        image: redis:latest
        ports:
          - "6379:6379"

    Then run:

    docker-compose up -d
  2. Manage database migrations: The project uses a built-in migration tool. All migration files are located in internal/infrastructure/database/migration/.

    • Create a new migration:

      go run cmd/main.go migration -a create -n create_users_table -d internal/infrastructure/database/migration

      (Replace create_users_table with your migration name)

    • Run all pending migrations:

      go run cmd/main.go migration -a migrate
    • Rollback the last migration:

      go run cmd/main.go migration -a rollback -s 1
    • Clean (drop all tables):

      go run cmd/main.go migration -a clean
    • List all migrations and their status:

      go run cmd/main.go migration -a list
  3. Run the HTTP Server:

    go run cmd/main.go run:server

    The application should start on the port specified in your .env file (default: 8080).

  4. Run the Background Worker:

    go run cmd/main.go run:worker

    This will start the worker process for handling background tasks (e.g., queue jobs).

Usage

This boilerplate provides a solid foundation for building Go applications. It's designed to be highly adjustable to your specific needs. You can:

  • Create new features: Leverage the layered architecture to add new functionalities by creating new handlers, services, and repositories.
  • Manage database migrations: Easily create and run database migrations to evolve your schema.
  • Send emails: Utilize the integrated email service to send various types of notifications.
  • Process background tasks: Use the queue system for asynchronous processing of tasks.
  • Integrate with external services: Extend the infrastructure layer to connect with other APIs or services.
  • Customize configuration: Adjust environment variables in the .env file to suit your deployment environment.

API Endpoints

All endpoints (except health check) are prefixed with /api/v1:

  • GET /health - Health check endpoint (no versioning)
  • POST /api/v1/auth/login - User login
  • POST /api/v1/auth/register - User registration
  • GET /api/v1/auth/profile - Get user profile (authenticated)
  • GET /api/v1/users - List users (authenticated)
  • POST /api/v1/example/upload - File upload example

Security Considerations

IMPORTANT for Production:

  1. Generate a strong AUTH_SECRET using: openssl rand -base64 32
  2. Update SERVER_ALLOW_ORIGINS to specific domains (remove *)
  3. Use HTTPS and uncomment HSTS header in security middleware
  4. Review and adjust rate limiting based on your needs
  5. Implement proper password complexity requirements
  6. Use a secrets management system for sensitive configuration

Configuration

The boilerplate includes extensive configuration options via environment variables:

Database:

  • Connection pool settings (max idle/open connections, connection lifetime)
  • Charset configuration
  • Debug query logging

Email:

  • Configurable from address (name and email)
  • SMTP settings with SSL/TLS support

Security:

  • Separate auth issuer and secret
  • Rate limiting (requests per minute)
  • CORS origins

Logging:

  • Configurable log level (debug, info, warn, error)
  • Daily log rotation
  • Dual output (console + JSON file)

See .env.example for all available configuration options.

Contributing

Contributions are welcome! Please feel free to open issues or submit pull requests.

License

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

About

A robust and scalable boilerplate for building Go applications with a layered architecture

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •