クイックスタート:5分で理解するポート&アダプターへのリファクタリング
プロトタイピングの段階では、http.HandlerFunc のコールバック内に直接SQLクエリを書き込むショートカットがよく使われます。初期段階ではこれで問題なく動作します。しかし、実際のPostgreSQLインスタンスを起動せずに価格計算ロジックや登録フローの検証を行おうとした瞬間、テストの実行速度は著しく低下してしまいます。
Alistair Cockburn氏は、このような結合を排除するためにヘキサゴナルアーキテクチャ(別名:ポート&アダプター)を提唱しました。その基本原則はシンプルです。「コアとなるビジネスロジックは、配信メカニズムやストレージエンジンに決して依存してはならない」ということです。これはクリーンアーキテクチャの思想とも深く共通しています。HTTPルーター、gRPCトランスポート、リレーショナルデータベースなどは単なる外部の詳細にすぎません。ドメインは常に純粋に保たれるべきです。
このアーキテクチャは以下の3つの主要コンポーネントで構成されます:
- コア・ドメイン(Core Domain):純粋なビジネスエンティティとドメインサービス。
- ポート(Ports):アプリケーションのインバウンドなユースケースと、アウトバウンドなインフラ要件を定義するGoのインターフェース。
- アダプター(Adapters):Chi/Ginのルートハンドラー、PostgreSQLリポジトリ、Kafkaプロデューサーなどの具体的な実装。
package main
import (
"context"
"errors"
"fmt"
)
// ドメインモデル:サードパーティへの依存関係なし
type User struct {
ID string
Email string
}
// 駆動されるポート(Driven Port):永続化のための外向きインターフェース
type UserRepository interface {
Save(ctx context.Context, user User) error
FindByID(ctx context.Context, id string) (*User, error)
}
// コアドメインサービス:純粋なビジネスロジック
type UserService struct {
repo UserRepository
}
func NewUserService(repo UserRepository) *UserService {
return &UserService{repo: repo}
}
func (s *UserService) Register(ctx context.Context, id, email string) error {
if email == "" {
return errors.New("メールアドレスは必須です")
}
if err := s.repo.Save(ctx, User{ID: id, Email: email}); err != nil {
return fmt.Errorf("ユーザー %s の保存中にエラーが発生しました: %w", id, err)
}
return nil
}
UserService は net/http も database/sql もインポートしていません。ネイティブなGoの構造体とコンシューマー所有のインターフェースのみを介してやり取りを行います。
ディープダイブ:ドメイン、ストレージ、トランスポートの分離
Goにおける循環参照(circular dependency)を防ぐため、技術レイヤーごとではなく機能的な責務ごとにリポジトリを構成します。
プロジェクト構成
cmd/
api/
main.go
internal/
core/
domain/
order.go
ports/
ports.go
services/
order_service.go
adapters/
handlers/
http_order.go
storage/
postgres_order.go
1. ドメインエンティティとポートの定義
ドメインモデルは internal/core/domain/order.go に分離します。これらの構造体は、データベースのアノテーションを持たずに状態とセンチネルエラーを保持します:
package domain
import "errors"
var ErrOrderNotFound = errors.New("注文が見つかりません")
type Order struct {
ID string
Amount float64
Status string
}
インターフェースの規約は internal/core/ports/ports.go で定義します。これにより、インカミングコマンドとアウトバウンドデータアクセスの境界が確立されます:
package ports
import (
"context"
"myapp/internal/core/domain"
)
// 駆動されるポート(Driven Port):データベースアダプターによって実装されるストレージの抽象化
type OrderRepository interface {
GetByID(ctx context.Context, id string) (*domain.Order, error)
Create(ctx context.Context, order domain.Order) error
}
// 駆動するポート(Driving Port):トランスポートアダプター(HTTP、gRPC、CLI)に公開されるアプリケーションAPI
type OrderService interface {
PlaceOrder(ctx context.Context, id string, amount float64) error
FetchOrder(ctx context.Context, id string) (*domain.Order, error)
}
2. ドメインサービスの実装
ビジネスバリデーションは internal/core/services/order_service.go 内で実行されます。サービスはリポジトリポートに対してドメインロジックを調整します:
package services
import (
"context"
"errors"
"fmt"
"myapp/internal/core/domain"
"myapp/internal/core/ports"
)
type orderService struct {
repo ports.OrderRepository
}
func NewOrderService(repo ports.OrderRepository) ports.OrderService {
return &orderService{repo: repo}
}
func (s *orderService) PlaceOrder(ctx context.Context, id string, amount float64) error {
if amount <= 0 {
return errors.New("注文金額は0より大きい必要があります")
}
order := domain.Order{
ID: id,
Amount: amount,
Status: "PENDING",
}
if err := s.repo.Create(ctx, order); err != nil {
return fmt.Errorf("注文 %s の登録に失敗しました: %w", id, err)
}
return nil
}
func (s *orderService) FetchOrder(ctx context.Context, id string) (*domain.Order, error) {
order, err := s.repo.GetByID(ctx, id)
if err != nil {
return nil, fmt.Errorf("注文 %s の取得に失敗しました: %w", id, err)
}
return order, nil
}
3. 駆動するHTTPアダプターの構築
受け取ったHTTPリクエストは internal/adapters/handlers/http_order.go で処理されます。ハンドラーはペイロードをアンマーシャリングし、駆動ポートを呼び出し、ドメインの実行結果をHTTPステータスコードにマッピングします:
package handlers
import (
"encoding/json"
"net/http"
"myapp/internal/core/ports"
)
type HTTPOrderHandler struct {
service ports.OrderService
}
func NewHTTPOrderHandler(service ports.OrderService) *HTTPOrderHandler {
return &HTTPOrderHandler{service: service}
}
type CreateOrderRequest struct {
ID string `json:"id"`
Amount float64 `json:"amount"`
}
func (h *HTTPOrderHandler) Create(w http.ResponseWriter, r *http.Request) {
var req CreateOrderRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, `{"error":"無効なJSONペイロードです"}`, http.StatusBadRequest)
return
}
if err := h.service.PlaceOrder(r.Context(), req.ID, req.Amount); err != nil {
http.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
w.WriteHeader(http.StatusCreated)
}
4. 駆動されるデータベースアダプターの構築
ストレージ操作は internal/adapters/storage/postgres_order.go に配置します。このアダプターはクエリを実行し、SQLドライバのエラーをドメインエラーに変換します:
package storage
import (
"context"
"database/sql"
"errors"
"fmt"
"myapp/internal/core/domain"
"myapp/internal/core/ports"
)
var _ ports.OrderRepository = (*PostgresOrderRepo)(nil)
type PostgresOrderRepo struct {
db *sql.DB
}
func NewPostgresOrderRepo(db *sql.DB) *PostgresOrderRepo {
return &PostgresOrderRepo{db: db}
}
func (r *PostgresOrderRepo) Create(ctx context.Context, order domain.Order) error {
query := `INSERT INTO orders (id, amount, status) VALUES ($1, $2, $3)`
_, err := r.db.ExecContext(ctx, query, order.ID, order.Amount, order.Status)
if err != nil {
return fmt.Errorf("注文のINSERT実行中にエラーが発生しました: %w", err)
}
return nil
}
func (r *PostgresOrderRepo) GetByID(ctx context.Context, id string) (*domain.Order, error) {
query := `SELECT id, amount, status FROM orders WHERE id = $1`
row := r.db.QueryRowContext(ctx, query, id)
var o domain.Order
if err := row.Scan(&o.ID, &o.Amount, &o.Status); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrOrderNotFound
}
return nil, fmt.Errorf("注文レコードのスキャン中にエラーが発生しました: %w", err)
}
return &o, nil
}
テスト:インメモリモックを用いたマイクロ秒レベルのフィードバックループ
Testcontainersに依存した統合テストスイートでは、PostgreSQLを起動してスキーママイグレーションを適用するだけで25〜45秒かかることがよくあります。一方、インメモリのポートモックに対して作成されたテストであれば、500件のテストスイートでも15ミリ秒未満で完了します。
package services_test
import (
"context"
"sync"
"testing"
"myapp/internal/core/domain"
"myapp/internal/core/services"
)
type mockOrderRepo struct {
mu sync.RWMutex
orders map[string]domain.Order
}
func newMockOrderRepo() *mockOrderRepo {
return &mockOrderRepo{orders: make(map[string]domain.Order)}
}
func (m *mockOrderRepo) Create(ctx context.Context, order domain.Order) error {
m.mu.Lock()
defer m.mu.Unlock()
m.orders[order.ID] = order
return nil
}
func (m *mockOrderRepo) GetByID(ctx context.Context, id string) (*domain.Order, error) {
m.mu.RLock()
defer m.mu.RUnlock()
o, exists := m.orders[id]
if !exists {
return nil, domain.ErrOrderNotFound
}
return &o, nil
}
func TestPlaceOrder_ValidAmount(t *testing.T) {
repo := newMockOrderRepo()
svc := services.NewOrderService(repo)
err := svc.PlaceOrder(context.Background(), "ord-101", 49.99)
if err != nil {
t.Fatalf("予期しないエラーです: %v", err)
}
stored, err := repo.GetByID(context.Background(), "ord-101")
if err != nil {
t.Fatalf("リポジトリ内に注文が見つかりません: %v", err)
}
if stored.Status != "PENDING" {
t.Errorf("ステータスは PENDING を期待しましたが、実際は %q でした", stored.Status)
}
if stored.Amount != 49.99 {
t.Errorf("金額は 49.99 を期待しましたが、実際は %.2f でした", stored.Amount)
}
}
func TestPlaceOrder_InvalidAmount(t *testing.T) {
repo := newMockOrderRepo()
svc := services.NewOrderService(repo)
err := svc.PlaceOrder(context.Background(), "ord-102", -5.00)
if err == nil {
t.Fatal("負の金額に対してバリデーションエラーを期待しましたが、nilが返されました")
}
}
コードの編集中に go test -race ./internal/core/... を繰り返し実行してみてください。Dockerソケットのリークやスキーマ破棄に伴う遅延、テスト間での状態汚染などを完全に回避できます。
本番運用のガイドライン
- インターフェースはコンシューマー起点で設計する:Goでは、パッケージはインターフェースを受け取り構造体を返すのが基本です(Accept interfaces, return structs)。ドメインインターフェースは、サービスが実際に呼び出すメソッドだけに絞り込みましょう。20個もメソッドが並ぶ肥大化したリポジトリインターフェースは避けるべきです。
- ドメインモデルへのタグ混入を防ぐ:
internal/core/domainの構造体にgorm:"column:..."やbson:"..."といったタグを埋め込まないでください。ドメインの定義は、外部のORMやドライバから完全に独立していなければなりません。 - main.goで明示的に依存関係を配線する:リフレクションを多用する重厚なDIコンテナは避けましょう。
cmd/api/main.go内で10行程度の明示的なコンストラクタ配線を行うか、必要に応じてGoogle Wireによるコンパイル時依存性注入を活用するだけで、標準のリンターで検証可能な、コンパイル時に確定する見通しの良いコールグラフが得られます。 - ドライバの境界でエラーを変換する:アダプター内で
sql.ErrNoRowsやMongoのErrNoDocumentsをdomain.ErrOrderNotFoundにマッピングします。これにより、HTTPハンドラー側でベンダー固有のエラー文字列をパースすることなく、即座に404レスポンスを返すことができます。
