Skip to content
golang-clean-architecture logo

Golang Clean Architecture

golang-clean-architecture

Clean Architecture audit for Go services. Use when reviewing layered architecture, dependency rules, or gRPC/usecase/repository patterns. Ensures proper separation of concerns and dependency inversion.

SKILL.md

Full skill instructions

Golang Clean Architecture

Audit Go services for Clean Architecture compliance. Ensures proper layering, dependency rules, and separation of concerns in gRPC → Usecase → Repository → Domain architectures.

When to Apply

Use this skill when:

  • Auditing service architecture
  • Reviewing new features for layer violations
  • Refactoring toward Clean Architecture
  • Code review for dependency rules
  • Planning service structure
  • Migrating to layered architecture
  • Ensuring testability through dependency injection

Architecture Layers

┌─────────────────────────────────────┐
│  Delivery (gRPC/​HTTP/​GraphQL)       │ ← Thin, no business logic
├─────────────────────────────────────┤
│  Usecase (Business Logic)           │ ← Orchestration
├─────────────────────────────────────┤
│  Repository (Data Access)           │ ← CRUD only
├─────────────────────────────────────┤
│  Domain (Entities/​Interfaces)       │ ← Pure business logic
└─────────────────────────────────────┘

Dependency Rule: Dependencies point INWARD only (toward domain).

Rules Covered (9 total)

High-Impact Patterns (4)

  • high-business-logic-handler - Keep delivery layer thin
  • high-business-logic-repository - No business logic in data layer
  • high-constructor-creates-deps - Inject dependencies, don't create
  • high-transaction-in-repository - Transactions belong in usecase

Architecture Rules (5)

  • arch-domain-import-infra - Domain must not import infrastructure
  • arch-concrete-dependency - Depend on interfaces, not concrete types
  • arch-repository-business-logic - Repositories do CRUD only
  • arch-usecase-orchestration - Usecases orchestrate, entities decide
  • arch-interface-segregation - Small, consumer-defined interfaces

Common Violations

❌ Business Logic in Handler

// gRPC handler doing calculations
func (h *Handler) CreateOrder(ctx context.Context, req *pb.Request) (*pb.Response, error) {
    total := req.Price * req.Quantity // BAD: calculation in handler
    discount := total * 0.1           // BAD: business rules in delivery layer
    
    order := &domain.Order{
        Total: total - discount,
    }
    return h.orderRepo.Save(ctx, order)
}

✅ Business Logic in Usecase

// Handler delegates to usecase
func (h *Handler) CreateOrder(ctx context.Context, req *pb.Request) (*pb.Response, error) {
    order, err := h.orderUsecase.Create(ctx, req.Price, req.Quantity)
    if err != nil {
        return nil, err
    }
    return &pb.Response{OrderId: order.ID}, nil
}

// Usecase contains business logic
func (u *OrderUsecase) Create(ctx context.Context, price, quantity int) (*domain.Order, error) {
    total := price * quantity      // GOOD: calculation in usecase
    discount := total * 0.1        // GOOD: business rules in usecase
    
    order := &domain.Order{
        Total: total - discount,
    }
    return u.orderRepo.Save(ctx, order)
}

❌ Repository with Business Logic

// Repository doing validation and business rules
func (r *OrderRepo) Save(ctx context.Context, order *domain.Order) error {
    if order.Total < 0 {                    // BAD: validation in repository
        return errors.New("invalid total")
    }
    if order.Total > 1000000 {              // BAD: business rule in repository
        order.Status = "needs_approval"     // BAD: state change in repository
    }
    return r.db.Create(order)
}

✅ Repository Does CRUD Only

// Repository only handles data persistence
func (r *OrderRepo) Save(ctx context.Context, order *domain.Order) error {
    return r.db.Create(order) // GOOD: simple CRUD
}

// Validation happens in usecase or domain entity
func (u *OrderUsecase) Create(ctx context.Context, price, quantity int) (*domain.Order, error) {
    order := domain.NewOrder(price, quantity) // Entity validates itself
    if err := order.Validate(); err != nil {    // GOOD: validation in domain
        return nil, err
    }
    if order.NeedsApproval() {                  // GOOD: business rule in domain
        order.Status = "needs_approval"
    }
    return u.orderRepo.Save(ctx, order)
}

Trigger Phrases

This skill activates when you say:

  • "Audit architecture"
  • "Check layer dependencies"
  • "Review Clean Architecture"
  • "Verify separation of concerns"
  • "Check dependency rules"
  • "Review usecase/​repository pattern"
  • "Check for layer violations"
  • "Audit service structure"

How to Use

For Architecture Audit

  1. Identify all layers in the codebase
  2. Check dependency directions (must point inward)
  3. Verify each layer's responsibilities
  4. Flag violations with specific rule references

For Code Review

  1. Identify which layer the code belongs to
  2. Check against layer-specific rules
  3. Verify dependencies are injected, not created
  4. Ensure interfaces are defined by consumers

Output Format

## Architecture Violations: X

### [Rule Name] (File: path/​to/​file.go)
**Layer**: Delivery / Usecase / Repository / Domain
**Issue**: Brief description of violation
**Impact**: Tight coupling / Untestable / Wrong responsibility
**Fix**: Suggested correction
**Example**:
```go
// Corrected code

Related Skills

Philosophy

Based on Uncle Bob's Clean Architecture:

  • Independence - Business rules don't depend on frameworks, UI, or databases
  • Testability - Business logic can be tested without external dependencies
  • Flexibility - Easy to swap implementations (e.g., change database)
  • Maintainability - Clear boundaries make changes localized

Key Principle: The inner circles know nothing about the outer circles.

Notes

  • Rules enforce separation of concerns in Go services
  • Particularly focused on gRPC/​usecase/​repository pattern
  • Emphasizes dependency injection for testability
  • All examples follow Clean Architecture principles

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View