Goca CLI Code Generator

repository·master·Indexed 43 days ago

https://github.com/sazardev/goca

A CLI tool for scaffolding Go projects based on Clean Architecture principles. Goca automates the creation of Domain, Use Case, Adapter, and Infrastructure layers to reduce boilerplate and enforce best practices like Dependency Injection and the Repository Pattern. It includes commands for initializing projects, generating complete features with automatic integration, and creating individual architectural components.

Tokens
135.7K
Snippets
442
Records
623
Agent score
54%

What's inside Goca

  1. Understand the Goca project structure

    master

    Goca follows Clean Architecture principles, organizing code into layers to ensure a clear separation of concerns. The project is divided into cmd/ for entry points, internal/ for private application logic, pkg/ for public libraries, and migrations/ for database changes.

    Directory Overview

    • cmd/ : Application entry points (e.g., cmd/server/main.go).
    • internal/ : Private application code containing the core layers:
      • domain/: Business entities and core rules.
      • usecase/: Business logic and application rules.
      • repository/: Data access implementations.
      • handler/: Delivery mechanisms (e.g., HTTP).
      • di/: Dependency injection wiring.
      • messages/: Errors and constants.
    • pkg/ : Public libraries that can be imported by other projects (e.g., config/, logger/).
    • migrations/ : SQL database migration files.
    myproject/
    ├── cmd/                    # Application entry points
    │   └── server/
    │       └── main.go
    ├── internal/               # Private application code
    │   ├── domain/            # Business entities
    │   ├── usecase/           # Business logic
    │   ├── repository/        # Data access
    │   ├── handler/           # Delivery mechanisms
    │   ├── di/                # Dependency injection
    │   └── messages/          # Errors and constants
    ├── pkg/                    # Public libraries
    │   ├── config/            # Configuration loading
    │   └── logger/            # Structured logging
    ├── migrations/             # Database migrations
  2. Goca CLI Command Overview

    master

    Goca provides a comprehensive set of commands to generate Clean Architecture components and manage your project structure. Commands are categorized into Project Initialization, Complete Features, Layer-Specific Generation, Configuration & Templates, Utilities, and Testing.

    Command Categories

    Project Initialization

    • goca init: Initialize a new Clean Architecture project.

    Complete Features

    • goca feature: Generate a complete feature with all layers.
    • goca integrate: Integrate existing features with DI and routing.

    Layer-Specific Generation

    • Domain Layer: goca entity (Generate domain entities).
    • Application Layer: goca usecase (Generate use cases and DTOs), goca interfaces (Generate interface contracts).
    • Infrastructure Layer: goca repository (Generate repositories).
    • Adapter Layer: goca handler (Generate handlers like HTTP, gRPC, CLI), goca middleware (Generate composable HTTP middleware).

    Configuration & Templates

    • goca config: Manage .goca.yaml configuration files.
    • goca template: Manage custom code generation templates.

    Utilities

    • goca di: Generate dependency injection container.
    • goca messages: Generate error messages and constants.
    • goca mocks: Generate testify/mock mocks for all interfaces.
    • goca doctor: Check project health and Clean Architecture structure.
    • goca analyze: Deep self-analysis (architecture, security, quality, etc.).
    • goca ci: Generate CI/CD pipeline configuration (GitHub Actions).
    • goca mcp-server: Start MCP server for AI assistant integration.
    • goca upgrade: Upgrade project configuration to current Goca version.
    • goca version: Display version information.

    Testing

    • goca test-integration: Generate integration test scaffolding.
  3. Benefits of using the goca feature command

    master

    The goca feature command is a high-level generator that provides a complete, production-ready feature set. It automates the creation of multiple layers while enforcing Clean Architecture and SOLID principles.

    Key Deliverables

    • Complete CRUD API: Generates all necessary endpoints in seconds.
    • Clean Architecture Enforcement: Separates business logic, domain, and infrastructure.
    • Automatic Validation: Includes validation at all layers.
    • Auto-Integration: Automatically wires the new feature into the Dependency Injection (DI) container and the HTTP router.
    • Production Readiness: Includes Swagger documentation support and prepared database migrations.

    Implemented Best Practices

    • Single Responsibility Principle (SRP)
    • Dependency Inversion (DIP)
    • Interface Segregation (ISP)
    • Domain-Driven Design (DDD)
    • Proper HTTP Status Codes and Error Handling
  4. Benefits of Clean Architecture in Goca projects

    master

    Using the Clean Architecture patterns enforced by Goca provides several key advantages:

    1. Framework Independence: You can switch web frameworks (e.g., Gin to Echo) by only changing the internal/handler/http layer. The Use Case and Domain layers remain untouched.
    2. Database Independence: You can swap databases (e.g., PostgreSQL to MongoDB) by changing the internal/repository implementation. Use Cases remain unchanged because they depend on interfaces.
    3. UI Independence: You can add new entry points (e.g., gRPC) alongside existing ones (e.g., REST) without affecting the core business logic.
    4. Complete Testability: Enables a full testing pyramid from unit tests (domain/usecase) to integration tests (repository) and E2E tests (handlers).
  5. Understand the Goca wiki structure

    master

    The documentation is organized into three main functional areas:

    Getting Started

    • Home.md: Project overview.
    • Installation.md: Installation instructions.
    • Getting-Started.md: Quick start guide.
    • Complete-Tutorial.md: A full e-commerce tutorial walkthrough.

    Command Reference

    Detailed documentation for the CLI commands:

    • Command-Init.md: The goca init command.
    • Command-Feature.md: The goca feature command.
    • Command-Version.md: The goca version command.

    Architecture & Concepts

    Deep dives into the underlying design:

    • Clean-Architecture.md: Principles of Clean Architecture applied to Goca.
    • Project-Structure.md: How the generated directories are organized.
  6. What is Clean Architecture and its core principles

    master

    Clean Architecture is a software design philosophy that organizes code into layers with clear responsibilities. Dependencies must always point inward toward the core business logic, following the Dependency Rule: source code dependencies must only point toward higher-level policies (the inner layers).

    Core Principles

    • Independence of Frameworks: Business logic does not depend on external libraries.
    • Testability: Business rules can be tested in isolation without requiring a UI, database, or external services.
    • Independence of UI: The user interface can be changed without affecting the core business logic.
    • Independence of Database: Databases can be swapped without affecting business rules.
    • Independence of External Systems: The business logic remains unaware of the outside world.
  7. What is a Use Case in Clean Architecture?

    master

    A use case is an application service that coordinates domain entities and infrastructure to fulfill a specific user or system goal. It answers the question: "What can the application do?"

    Core Responsibilities

    • Orchestration: Coordinates multiple domain entities, repositories, and external services to complete a workflow. It applies business rules rather than containing them.
    • Data Flow Control: Manages data movement between the UI layer and the domain layer, transforming external requests into domain operations and domain results into external responses.
    • Application Logic: Implements application-specific rules that depend on the use case context rather than core business concepts.
    • Transaction Management: Defines transaction boundaries to ensure operations are atomic.
    • Permission and Security: Enforces authorization rules to check if a user is permitted to perform an operation.
  8. What is the Repository Pattern in Clean Architecture?

    master

    The Repository pattern is an abstraction that mediates between the domain layer and data mapping layers. It acts as an in-memory collection of domain objects, providing a domain-centric API while hiding the complexities of database interactions, query construction, and persistence mechanisms.

    Core Responsibilities

    • Abstraction: Hides data access details. The domain layer uses interfaces expressing intent (e.g., FindUserByEmail) rather than implementation (e.g., SELECT * FROM users...).
    • Collection Semantics: Treats data as collections of entities. You add, remove, and query entities using domain-meaningful methods.
    • Domain-Centric API: Methods use domain language and work with domain entities (e.g., Save(user) instead of Insert(tableName, columns)).
    • Testability: Interfaces allow replacing real database implementations with in-memory fakes for unit testing business logic.
    • Database Independence: Isolates database-specific code, allowing you to switch from PostgreSQL to MongoDB by only changing the repository implementation, not the domain logic.
  9. What is Clean Architecture in Goca?

    master

    Goca implements Uncle Bob's Clean Architecture by organizing code into concentric layers where dependencies only point towards the center. This ensures framework, UI, and database independence.

    Goca's implementation follows these layer color-coded concepts:

    • 🟡 Domain: Pure entities that contain no external dependencies.
    • 🔴 Use Cases: Application logic that utilizes clear Data Transfer Objects (DTOs).
    • 🟢 Adapters: Interfaces that adapt input and output (e.g., handlers, repositories).
    • 🔵 Infrastructure: Technology-specific implementations (e.g., database drivers, web frameworks).
  10. The Use Cases Layer

    master

    The Use Cases Layer, located in internal/usecase/, handles application-specific logic and orchestrates the flow of data between the Domain and the Adapters.

    What to include:

    • DTOs (Data Transfer Objects): Request and Response objects used to move data across layer boundaries.
    • Use Case Interfaces: Contracts defining what the application can do (e.g., UserUseCase).
    • Application Services: The actual implementation of the orchestration logic.
    • Repository Interfaces: Definitions of how data should be persisted (used by the Use Case to talk to the Infrastructure).

    What to avoid:

    • Presentation logic (HTTP/gRPC details).
    • Database implementation details.
    • Web framework logic.
    package usecase
    
    import (
        "context"
        "github.com/user/project/internal/domain"
    )
    
    // UserUseCase defines contracts for user use cases
    type UserUseCase interface {
        Create(ctx context.Context, req CreateUserRequest) (*UserResponse, error)
        GetByID(ctx context.Context, id uint) (*UserResponse, error)
    }
    
    // UserRepository defines contracts for persistence
    type UserRepository interface {
        Save(ctx context.Context, user *domain.User) error
        FindByID(ctx context.Context, id uint) (*domain.User, error)
    }
    
    // userUseCase implements application logic
    type userUseCase struct {
        userRepo UserRepository
    }
    
    func NewUserUseCase(userRepo UserRepository) UserUseCase {
        return &userUseCase{userRepo: userRepo}
    }
  11. Understand the generated Repository and Handler layers

    master

    Goca generates the infrastructure layers to handle data persistence and external communication:

    • Repository (🔵): Concrete implementations for specific databases (e.g., postgres). It handles raw SQL queries and maps database rows to Domain Entities.
    • HTTP Handler (🟢): Uses frameworks like gin to manage HTTP requests. It:
      • Binds JSON to DTOs.
      • Calls the appropriate Use Case method.
      • Maps domain errors (e.g., ErrUserNotFound) to HTTP status codes (e.g., 404 Not Found).
      • Returns JSON responses.
    • HTTP Routes (🟢): A dedicated file (e.g., user_routes.go) that registers all endpoints for the feature within a router group.
  12. Best practices and common errors for Goca Use Cases

    master

    When generating and implementing Use Cases with Goca, follow these architectural principles to ensure a clean implementation:

    ✅ Best Practices

    • Specific DTOs: Use distinct Data Transfer Objects (DTOs) for input and output operations to maintain strict boundaries.
    • Early validations: Perform data validation within the DTOs before the data reaches the domain layer.
    • Clear interfaces: Define explicit contracts for your use cases to ensure predictable behavior.
    • Context propagation: Always use context.Context in all method signatures to support cancellation and timeouts.

    ❌ Common Errors to Avoid

    • Business logic in use cases: Keep use cases focused on orchestration; business logic must reside in the domain layer.
    • Direct dependencies: Use cases should never access the database or HTTP layers directly; they must interact through interfaces/repositories.
    • Anemic DTOs: Avoid DTOs that lack validations or necessary behavior.
    • Mixing concerns: Do not mix different responsibilities (e.g., orchestration vs. business logic) within a single use case.