jpskill.com
🛠️ 開発・MCP コミュニティ

golang-enterprise-patterns

Go言語で、クリーンアーキテクチャやDDDなどのエンタープライズレベルの設計パターンを適用した、本番環境向けのアプリケーション構造を構築するSkill。

📜 元の英語説明(参考)

Enterprise-level Go architecture patterns including clean architecture, hexagonal architecture, DDD, and production-ready application structure.

🇯🇵 日本人クリエイター向け解説

一言でいうと

Go言語で、クリーンアーキテクチャやDDDなどのエンタープライズレベルの設計パターンを適用した、本番環境向けのアプリケーション構造を構築するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o golang-enterprise-patterns.zip https://jpskill.com/download/6914.zip && unzip -o golang-enterprise-patterns.zip && rm golang-enterprise-patterns.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/6914.zip -OutFile "$d\golang-enterprise-patterns.zip"; Expand-Archive "$d\golang-enterprise-patterns.zip" -DestinationPath $d -Force; ri "$d\golang-enterprise-patterns.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して golang-enterprise-patterns.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → golang-enterprise-patterns フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-17
取得日時
2026-05-17
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Golangエンタープライズパターン

このスキルでは、エンタープライズレベルのGoアプリケーションアーキテクチャ、デザインパターン、および本番環境に対応したコード構成に関するガイダンスを提供します。

このスキルを使用する場面

  • 複雑なビジネスロジックを持つ新しいGoアプリケーションを設計する際
  • クリーンアーキテクチャまたはヘキサゴナルアーキテクチャを実装する際
  • ドメイン駆動設計(DDD)の原則を適用する際
  • 大規模なGoコードベースを整理する際
  • チームの一貫性のためのパターンを確立する際

クリーンアーキテクチャ

レイヤー構造

/cmd
  /api           - HTTP/gRPCのエントリーポイント
  /worker        - バックグラウンドジョブランナー
/internal
  /domain        - ビジネスエンティティとインターフェース
  /application   - ユースケースとアプリケーションサービス
  /infrastructure
    /persistence - データベースの実装
    /messaging   - キューの実装
    /http        - HTTPクライアントの実装
  /interfaces
    /api         - HTTPハンドラー
    /grpc        - gRPCハンドラー
/pkg             - 共有ライブラリ(公開)

依存関係のルール

依存関係は内側のみに流れます。

Interfaces → Application → Domain
     ↓            ↓
Infrastructure (ドメインインターフェースを実装)

ドメイン層

// domain/user.go
package domain

import "time"

type UserID string

type User struct {
    ID        UserID
    Email     string
    Name      string
    CreatedAt time.Time
}

// UserRepository defines the contract for user persistence
type UserRepository interface {
    FindByID(ctx context.Context, id UserID) (*User, error)
    FindByEmail(ctx context.Context, email UserID) (*User, error)
    Save(ctx context.Context, user *User) error
    Delete(ctx context.Context, id UserID) error
}

// UserService defines domain business logic
type UserService interface {
    Register(ctx context.Context, email, name string) (*User, error)
    Authenticate(ctx context.Context, email, password string) (*User, error)
}

アプリケーション層

// application/user_service.go
package application

type UserServiceImpl struct {
    repo   domain.UserRepository
    hasher PasswordHasher
    logger Logger
}

func NewUserService(repo domain.UserRepository, hasher PasswordHasher, logger Logger) *UserServiceImpl {
    return &UserServiceImpl{repo: repo, hasher: hasher, logger: logger}
}

func (s *UserServiceImpl) Register(ctx context.Context, email, name string) (*domain.User, error) {
    // Check if user exists
    existing, err := s.repo.FindByEmail(ctx, email)
    if err != nil && !errors.Is(err, domain.ErrNotFound) {
        return nil, fmt.Errorf("checking existing user: %w", err)
    }
    if existing != nil {
        return nil, domain.ErrUserAlreadyExists
    }

    user := &domain.User{
        ID:        domain.UserID(uuid.New().String()),
        Email:     email,
        Name:      name,
        CreatedAt: time.Now(),
    }

    if err := s.repo.Save(ctx, user); err != nil {
        return nil, fmt.Errorf("saving user: %w", err)
    }

    return user, nil
}

ヘキサゴナルアーキテクチャ(Ports & Adapters)

ポートの定義

// ports/primary.go - Driving ports (入力)
package ports

type UserAPI interface {
    CreateUser(ctx context.Context, req CreateUserRequest) (*UserResponse, error)
    GetUser(ctx context.Context, id string) (*UserResponse, error)
}

// ports/secondary.go - Driven ports (出力)
type UserStorage interface {
    Save(ctx context.Context, user *domain.User) error
    FindByID(ctx context.Context, id string) (*domain.User, error)
}

type NotificationSender interface {
    SendWelcomeEmail(ctx context.Context, user *domain.User) error
}

アダプターの実装

// adapters/postgres/user_repository.go
package postgres

type UserRepository struct {
    db *sql.DB
}

func (r *UserRepository) Save(ctx context.Context, user *domain.User) error {
    query := `INSERT INTO users (id, email, name, created_at) VALUES ($1, $2, $3, $4)`
    _, err := r.db.ExecContext(ctx, query, user.ID, user.Email, user.Name, user.CreatedAt)
    return err
}

ドメイン駆動設計(DDD)

集約ルート

// domain/order/aggregate.go
package order

type Order struct {
    id         OrderID
    customerID CustomerID
    items      []OrderItem
    status     OrderStatus
    events     []DomainEvent
}

func NewOrder(customerID CustomerID) *Order {
    o := &Order{
        id:         OrderID(uuid.New().String()),
        customerID: customerID,
        status:     StatusPending,
    }
    o.recordEvent(OrderCreated{OrderID: o.id, CustomerID: customerID})
    return o
}

func (o *Order) AddItem(productID ProductID, quantity int, price Money) error {
    if o.status != StatusPending {
        return ErrOrderNotModifiable
    }
    o.items = append(o.items, OrderItem{
        ProductID: productID,
        Quantity:  quantity,
        Price:     price,
    })
    return nil
}

func (o *Order) Submit() error {
    if len(o.items) == 0 {
        return ErrEmptyOrder
    }
    o.status = StatusSubmitted
    o.recordEvent(OrderSubmitted{OrderID: o.id})
    return nil
}

値オブジェクト

// domain/money.go
type Money struct {
    amount   int64  // セント
    currency string
}

func NewMoney(amount int64, currency string) (Money, error) {
    if amount < 0 {
        return Money{}, ErrNegativeAmount
    }
    return Money{amount: amount, currency: currency}, nil
}

func (m Money) Add(other Money) (Money, error) {
    if m.currency != other.currency {
        return Money{}, ErrCurrencyMismatch
    }
    return Money{amount: m.amount + other.amount, currency: m.currency}, nil
}

ドメインイベント

// domain/events.go
type DomainEvent interface {
    EventName() string
    OccurredAt() time.Time
}

type OrderCreated struct {
    OrderID    OrderID
    CustomerID CustomerID
    occurredAt time.Time
}

func (e OrderCreated) EventName() string    { return "order.created" }
func (e OrderCreated) OccurredAt() time.Time { return e.occurredAt }

依存性注入

Wire-

📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Golang Enterprise Patterns

This skill provides guidance on enterprise-level Go application architecture, design patterns, and production-ready code organization.

When to Use This Skill

  • When designing new Go applications with complex business logic
  • When implementing clean architecture or hexagonal architecture
  • When applying Domain-Driven Design (DDD) principles
  • When organizing large Go codebases
  • When establishing patterns for team consistency

Clean Architecture

Layer Structure

/cmd
  /api           - HTTP/gRPC entry points
  /worker        - Background job runners
/internal
  /domain        - Business entities and interfaces
  /application   - Use cases and application services
  /infrastructure
    /persistence - Database implementations
    /messaging   - Queue implementations
    /http        - HTTP client implementations
  /interfaces
    /api         - HTTP handlers
    /grpc        - gRPC handlers
/pkg             - Shared libraries (public)

Dependency Rule

Dependencies flow inward only:

Interfaces → Application → Domain
     ↓            ↓
Infrastructure (implements domain interfaces)

Domain Layer

// domain/user.go
package domain

import "time"

type UserID string

type User struct {
    ID        UserID
    Email     string
    Name      string
    CreatedAt time.Time
}

// UserRepository defines the contract for user persistence
type UserRepository interface {
    FindByID(ctx context.Context, id UserID) (*User, error)
    FindByEmail(ctx context.Context, email string) (*User, error)
    Save(ctx context.Context, user *User) error
    Delete(ctx context.Context, id UserID) error
}

// UserService defines domain business logic
type UserService interface {
    Register(ctx context.Context, email, name string) (*User, error)
    Authenticate(ctx context.Context, email, password string) (*User, error)
}

Application Layer

// application/user_service.go
package application

type UserServiceImpl struct {
    repo   domain.UserRepository
    hasher PasswordHasher
    logger Logger
}

func NewUserService(repo domain.UserRepository, hasher PasswordHasher, logger Logger) *UserServiceImpl {
    return &UserServiceImpl{repo: repo, hasher: hasher, logger: logger}
}

func (s *UserServiceImpl) Register(ctx context.Context, email, name string) (*domain.User, error) {
    // Check if user exists
    existing, err := s.repo.FindByEmail(ctx, email)
    if err != nil && !errors.Is(err, domain.ErrNotFound) {
        return nil, fmt.Errorf("checking existing user: %w", err)
    }
    if existing != nil {
        return nil, domain.ErrUserAlreadyExists
    }

    user := &domain.User{
        ID:        domain.UserID(uuid.New().String()),
        Email:     email,
        Name:      name,
        CreatedAt: time.Now(),
    }

    if err := s.repo.Save(ctx, user); err != nil {
        return nil, fmt.Errorf("saving user: %w", err)
    }

    return user, nil
}

Hexagonal Architecture (Ports & Adapters)

Port Definitions

// ports/primary.go - Driving ports (input)
package ports

type UserAPI interface {
    CreateUser(ctx context.Context, req CreateUserRequest) (*UserResponse, error)
    GetUser(ctx context.Context, id string) (*UserResponse, error)
}

// ports/secondary.go - Driven ports (output)
type UserStorage interface {
    Save(ctx context.Context, user *domain.User) error
    FindByID(ctx context.Context, id string) (*domain.User, error)
}

type NotificationSender interface {
    SendWelcomeEmail(ctx context.Context, user *domain.User) error
}

Adapter Implementations

// adapters/postgres/user_repository.go
package postgres

type UserRepository struct {
    db *sql.DB
}

func (r *UserRepository) Save(ctx context.Context, user *domain.User) error {
    query := `INSERT INTO users (id, email, name, created_at) VALUES ($1, $2, $3, $4)`
    _, err := r.db.ExecContext(ctx, query, user.ID, user.Email, user.Name, user.CreatedAt)
    return err
}

Domain-Driven Design (DDD)

Aggregate Roots

// domain/order/aggregate.go
package order

type Order struct {
    id         OrderID
    customerID CustomerID
    items      []OrderItem
    status     OrderStatus
    events     []DomainEvent
}

func NewOrder(customerID CustomerID) *Order {
    o := &Order{
        id:         OrderID(uuid.New().String()),
        customerID: customerID,
        status:     StatusPending,
    }
    o.recordEvent(OrderCreated{OrderID: o.id, CustomerID: customerID})
    return o
}

func (o *Order) AddItem(productID ProductID, quantity int, price Money) error {
    if o.status != StatusPending {
        return ErrOrderNotModifiable
    }
    o.items = append(o.items, OrderItem{
        ProductID: productID,
        Quantity:  quantity,
        Price:     price,
    })
    return nil
}

func (o *Order) Submit() error {
    if len(o.items) == 0 {
        return ErrEmptyOrder
    }
    o.status = StatusSubmitted
    o.recordEvent(OrderSubmitted{OrderID: o.id})
    return nil
}

Value Objects

// domain/money.go
type Money struct {
    amount   int64  // cents
    currency string
}

func NewMoney(amount int64, currency string) (Money, error) {
    if amount < 0 {
        return Money{}, ErrNegativeAmount
    }
    return Money{amount: amount, currency: currency}, nil
}

func (m Money) Add(other Money) (Money, error) {
    if m.currency != other.currency {
        return Money{}, ErrCurrencyMismatch
    }
    return Money{amount: m.amount + other.amount, currency: m.currency}, nil
}

Domain Events

// domain/events.go
type DomainEvent interface {
    EventName() string
    OccurredAt() time.Time
}

type OrderCreated struct {
    OrderID    OrderID
    CustomerID CustomerID
    occurredAt time.Time
}

func (e OrderCreated) EventName() string    { return "order.created" }
func (e OrderCreated) OccurredAt() time.Time { return e.occurredAt }

Dependency Injection

Wire-Style DI

// wire.go
//+build wireinject

func InitializeApp(cfg *config.Config) (*App, error) {
    wire.Build(
        NewDatabase,
        NewUserRepository,
        NewUserService,
        NewHTTPServer,
        NewApp,
    )
    return nil, nil
}

Manual DI (Preferred for Simplicity)

// main.go
func main() {
    cfg := config.Load()

    db := database.Connect(cfg.DatabaseURL)

    userRepo := postgres.NewUserRepository(db)
    orderRepo := postgres.NewOrderRepository(db)

    userService := application.NewUserService(userRepo)
    orderService := application.NewOrderService(orderRepo, userRepo)

    handler := api.NewHandler(userService, orderService)
    server := http.NewServer(cfg.Port, handler)

    server.Run()
}

Error Handling Patterns

Custom Error Types

// domain/errors.go
type Error struct {
    Code    string
    Message string
    Err     error
}

func (e *Error) Error() string {
    if e.Err != nil {
        return fmt.Sprintf("%s: %s: %v", e.Code, e.Message, e.Err)
    }
    return fmt.Sprintf("%s: %s", e.Code, e.Message)
}

func (e *Error) Unwrap() error { return e.Err }

var (
    ErrNotFound         = &Error{Code: "NOT_FOUND", Message: "resource not found"}
    ErrUserAlreadyExists = &Error{Code: "USER_EXISTS", Message: "user already exists"}
    ErrInvalidInput     = &Error{Code: "INVALID_INPUT", Message: "invalid input"}
)

Configuration Management

// config/config.go
type Config struct {
    Server   ServerConfig
    Database DatabaseConfig
    Redis    RedisConfig
}

func Load() (*Config, error) {
    cfg := &Config{}

    cfg.Server.Port = getEnvInt("PORT", 8080)
    cfg.Server.ReadTimeout = getEnvDuration("READ_TIMEOUT", 30*time.Second)

    cfg.Database.URL = mustGetEnv("DATABASE_URL")
    cfg.Database.MaxConns = getEnvInt("DB_MAX_CONNS", 25)

    return cfg, nil
}

Best Practices

  1. Keep domain pure - No framework dependencies in domain layer
  2. Interface segregation - Small, focused interfaces
  3. Dependency inversion - Depend on abstractions, not concretions
  4. Explicit dependencies - Pass dependencies via constructor
  5. Fail fast - Validate at boundaries, trust internal code
  6. Make illegal states unrepresentable - Use types to enforce invariants