プロジェクト構造
Go プロジェクトアーキテクチャパターン:フラット構造と DDD。
フラットプロジェクト構造(Lightweight DDD / CRUD-heavy)
project-root/
├── cmd/
│ └── api/
│ └── main.go # エントリポイント:DB、Router、DI 初期化
├── internal/
│ ├── config/
│ │ └── config.go # 環境変数 / 設定読み込み
│ ├── order/ # リソースモジュール
│ │ ├── model.go # Entity / Value Object(純粋なデータ構造)
│ │ ├── repository.go # Repository interface + シンプルな DB 実装
│ │ ├── service.go # ビジネスロジック / Use Case
│ │ └── handler.go # HTTP Handler / Router
│ ├── user/ # 別のリソースモジュール、同じ構造
│ │ ├── model.go
│ │ ├── repository.go
│ │ ├── service.go
│ │ └── handler.go
│ └── util/ # ユーティリティ関数 / helper
│ └── logger.go
├── scripts/ # migration、seed またはその他のツールスクリプト
├── test/ # 統合テスト / fixtures
└── go.modフラット構造の説明
| ファイル | 責任 |
|---|---|
| model.go | Entity / Value Object、純粋なデータオブジェクト、DB や HTTP ロジックを含まない |
| repository.go | Repository interface + シンプルな実装(DB CRUD)、service が呼び出す |
| service.go | ビジネスロジック / Use Case、フローオーケストレーション、repository を呼び出す |
| handler.go | HTTP / gRPC Handler、request を解析 → service を呼び出す → response を返す |
| util/logger.go | 共有ユーティリティ関数、ログ、helper、検証関数など |
呼び出しフロー:
HTTP Request → handler.go → service.go → repository.go → DBDDD(Domain-Driven Design)
project-root/
├── cmd/
│ └── api/
│ └── main.go # エントリポイント、依存関係の組み立て、HTTP Server 起動
├── internal/
│ ├── domain/ # コアビジネスロジック、フレームワークに依存しない
│ │ └── order/
│ │ ├── aggregate/ # Aggregate Root、コア動作を担う
│ │ │ └── order.go
│ │ ├── entity/ # 補助 Entity
│ │ │ └── line_item.go
│ │ ├── valueobject/ # Value Object、不変オブジェクト
│ │ │ ├── order_id.go
│ │ │ └── money.go
│ │ ├── repository/ # Repository Interface(Domain インターフェース)
│ │ │ └── order_repository.go
│ │ ├── service/ # Domain Service(Aggregate 間 / 複雑なルール)
│ │ │ └── order_domain_service.go
│ │ ├── event/ # Domain Event
│ │ │ └── order_created.go
│ │ └── factory/ # Aggregate Factory
│ │ └── order_factory.go
│ ├── application/ # システム Use Case(エントリ)
│ │ └── order/
│ │ ├── command/ # システム状態を変更
│ │ │ └── create_order.go
│ │ ├── query/ # データ読み取り
│ │ │ └── get_order.go
│ │ └── dto/ # Data Transfer Object
│ │ └── order_dto.go
│ ├── infrastructure/ # 技術詳細の実装
│ │ └── order/
│ │ ├── persistence/ # Repository 実装(MySQL, Postgres…)
│ │ │ └── mysql_order_repository.go
│ │ └── messaging/ # Kafka / RabbitMQ Publisher
│ │ └── kafka_publisher.go
│ └── interfaces/ # 外部インターフェース / API レイヤー
│ └── http/
│ └── order/
│ └── handler.go # HTTP handler、application のみを呼び出す
└── app/
└── bootstrap.go # プロジェクト組み立てポイント、DI / wiring正式 DDD の説明
| レイヤー | 責任 |
|---|---|
| domain | コアビジネスロジック、Aggregate / Entity / ValueObject / Domain Service / Repository Interface / Event / Factory を含む |
| application | システム Use Case、フローと transaction boundary を決定、外部に DTO を返す |
| infrastructure | 技術実装の詳細、Repository / Event Publisher / Messaging を実装 |
| interfaces | 外部インターフェース (HTTP/gRPC/CLI)、application レイヤーのみを呼び出す |
| app/bootstrap | DI / wiring、repository / service / use case / handler を構築 |
呼び出しフロー:
HTTP Request → interfaces/handler → application/command → domain/aggregate + domain/service → repository → DB