How to Implement Domain-Driven Design (DDD) in Go

Implement DDD in Go by separating domain logic, application services, and infrastructure into distinct packages with clear interfaces.

Implement Domain-Driven Design in Go by organizing your code into bounded contexts with clear interfaces and separating domain logic from infrastructure. Start by defining your core domain entities and interfaces in a domain package, then implement application services and infrastructure handlers in separate layers.

// domain/user.go
package domain

type User interface {
    ID() string
    Name() string
}

type UserService interface {
    GetByID(id string) (User, error)
}

// application/user_service.go
package application

import "yourapp/domain"

type userService struct {
    repo domain.UserRepository
}

func NewUserService(repo domain.UserRepository) domain.UserService {
    return &userService{repo: repo}
}

func (s *userService) GetByID(id string) (domain.User, error) {
    return s.repo.FindByID(id)
}

// infrastructure/postgres/user_repo.go
package postgres

import "yourapp/domain"

type userRepository struct {
    db *sql.DB
}

func NewUserRepository(db *sql.DB) domain.UserRepository {
    return &userRepository{db: db}
}

func (r *userRepository) FindByID(id string) (domain.User, error) {
    // SQL implementation here
    return nil, nil
}